我遇到了Java 8“Optional”容器的繁琐问题。我无法将Optional映射到“冒泡”另一个可选项。
假设我有一个RussianNestingDoll类
public class NestedOptionalTest {
public static void main(String[] args) {
RussianNestingDoll doll = RussianNestingDoll.createInstance(RussianNestingDoll.createInstance(RussianNestingDoll.createInstance()));
Optional<Optional<RussianNestingDoll>> thirdDollContents = doll.getInnerDoll().map(d -> d.getInnerDoll());
if (thirdDollContents.isPresent() && thirdDollContents.get().isPresent()) {
System.out.println(thirdDollContents.get().get());
}
else {
System.out.println("empty");
}
}
private static final class RussianNestingDoll {
private final Optional<RussianNestingDoll> innerDoll;
public Optional<RussianNestingDoll> getInnerDoll() {
return innerDoll;
}
private RussianNestingDoll(Optional<RussianNestingDoll> innerDoll) {
this.innerDoll = innerDoll;
}
public static RussianNestingDoll createInstance() {
return new RussianNestingDoll(Optional.empty());
}
public static RussianNestingDoll createInstance(RussianNestingDoll innerDoll) {
return new RussianNestingDoll(Optional.of(innerDoll));
}
}
}
不必使用嵌套的选项,而只是选择“冒泡”会很好。这样我可以只调用一次“isPresent()”和“get()”,而不是两次调用它们。有没有办法可以做到这一点?
答案 0 :(得分:8)
我不确定你想要什么,但你可以像这样重写你的代码:
RussianNestingDoll doll = RussianNestingDoll.get(RussianNestingDoll.get(RussianNestingDoll.get()));
String content = doll.getInnerDoll()
.flatMap(d -> d.getInnerDoll())
.map(d -> d.get().toString())
.orElse("empty");
System.out.println(content);
如果您想在之后使用玩偶:
Optional<RussianNestingDoll> thirdDoll = doll.getInnerDoll()
.flatMap(d -> d.getInnerDoll());
if (thirdDoll.isPresent()) {
System.out.println(thirdDoll.get());
}
else {
System.out.println("empty");
}
答案 1 :(得分:4)
您想要flatMap
吗?
thirdDollContents
.flatMap(Function.identity()) // un-nest, get back an Optional<RussianNestingDoll>
.get() // or isPresent()
如果flatMap
为Optional
,thirdDollContents
将返回空的empty
。