【发布时间】:2015-09-25 07:11:51
【问题描述】:
这是我目前所得到的:
Optional<Foo> firstChoice = firstChoice();
Optional<Foo> secondChoice = secondChoice();
return Optional.ofNullable(firstChoice.orElse(secondChoice.orElse(null)));
这让我觉得既可怕又浪费。如果 firstChoice 存在,我会不必要地计算 secondChoice。
还有一个更高效的版本:
Optional<Foo> firstChoice = firstChoice();
if(firstChoice.isPresent()) {
return firstChoice;
} else {
return secondChoice();
}
在这里,如果不复制映射器或声明另一个局部变量,我就无法将某些映射函数链接到末尾。所有这些都使得代码比要解决的实际问题更复杂。
我宁愿写这个:
return firstChoice().alternatively(secondChoice());
但是 Optional::alternatively 显然不存在。现在呢?
【问题讨论】:
-
...遇到空的问题...现在我们有两个问题。
-
顺便说一句,Paul Sandoz 刚刚发布了一个 changeset 进行审查,其中介绍了
Optional.or()方法,这正是您想要的:firstChoice().or(this::secondChoice)。更多信息请访问JDK-8080418。在 Java-9 时代,我们会很高兴!