英文:
Setting String value from either one object field
问题
String Name = null;
Optional<String> optA = Optional.ofNullable(obj1.getX())
.map(a -> a.getXX())
.map(b -> b.getName());
if (optA.isPresent()) {
name = optA.get();
} else {
Optional<String> optB = Optional.ofNullable(obj1.getY())
.map(a -> a.getYY())
.map(b -> b.getYYY())
.map(c -> c.getName());
if (optB.isPresent()) {
name = optB.get();
}
}
英文:
How can I make my code look better?
I want to set String Name to ob1j.getX().getXX().getName() if it is present, otherwise I would set name to obj1.getY().getYY().getYYY().getName(). I'm also using Optional to perform null check.
Is this the correct way to do it ?
I'm using JDK8 so 'ifPresentOrElse' is not an option.
String Name = null;
Optional<String> optA = Optional.ofNullable(obj1.getX())
.map(a -> a.getXX())
.map(b -> b.getName())
if (optA.isPresent()) {
name = optA.get();
} else {
Optional<String> optB = Optional.ofNullable(obj1.getY())
.map(a -> a.getYY())
.map(b -> b.getYYY())
.map(c -> c.getName())
if (optB.isPresent()) {
name = optB.get();
}
}
答案1
得分: 0
你可以这样做:
name = Stream.of(
Optional.ofNullable(obj1.getX()).map(X::getXX).map(XX::getName),
Optional.ofNullable(obj1.getY()).map(Y::getYY).map(YY::getYYY).map(YYY::getName)
)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst().orElse(null);
或者对于延迟处理,你可以像这样使用 Supplier
:
List<Supplier<Optional<String>>> suppliers = Arrays.asList(
() -> Optional.ofNullable(obj1.getX()).map(X::getXX).map(XX::getName),
() -> Optional.ofNullable(obj1.getY()).map(Y::getYY).map(YY::getYYY).map(YYY::getName));
name = suppliers.stream()
.map(Supplier::get)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst().orElse(null);
英文:
You can do like this:
name = Stream.of(
Optional.ofNullable(obj1.getX()).map(X::getXX).map(XX::getName),
Optional.ofNullable(obj1.getY()).map(Y::getYY).map(YY::getYYY).map(YYY::getName)
)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst().orElse(null);
Or for lazy processing you use Supplier
like this:
List<Supplier<Optional<String>>> suppliers =Arrays.asList(
() -> Optional.ofNullable(obj1.getX()).map(X::getXX).map(XX::getName),
() -> Optional.ofNullable(obj1.getY()).map(Y::getYY).map(YY::getYYY).map(YYY::getName));
name = suppliers.stream()
.map(Supplier::get)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst().orElse(null);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论