java – 映射嵌套可选?

我有点遇到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()”,而不是两次调用它们.有没有办法可以做到这一点?

最佳答案
我不太确定你想要什么,但你可以像这样重写你的代码:

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");
}

转载注明原文:java – 映射嵌套可选? - 代码日志