Seb*_*off 32 java optional java-8
这是我到目前为止所得到的:
Optional<Foo> firstChoice = firstChoice();
Optional<Foo> secondChoice = secondChoice();
return Optional.ofNullable(firstChoice.orElse(secondChoice.orElse(null)));
Run Code Online (Sandbox Code Playgroud)
这让我觉得既丑陋又浪费.如果firstChoice存在,我不必要地计算secondChoice.
还有一个更高效的版本:
Optional<Foo> firstChoice = firstChoice();
if(firstChoice.isPresent()) {
return firstChoice;
} else {
return secondChoice();
}
Run Code Online (Sandbox Code Playgroud)
在这里,我无法将一些映射函数链接到最终,而无需复制映射器或声明另一个局部变量.所有这些使得代码比实际解决的问题更复杂.
我宁愿写这个:
return firstChoice().alternatively(secondChoice());
Run Code Online (Sandbox Code Playgroud)
但是Optional ::或者显然不存在.怎么办?
mar*_*ran 42
试试这个:
firstChoice().map(Optional::of)
.orElseGet(this::secondChoice);
Run Code Online (Sandbox Code Playgroud)
map方法为您提供了一个Optional<Optional<Foo>>.然后,该orElseGet方法将其展平为一个Optional<Foo>.secondChoice仅在firstChoice()返回空可选项时才会计算该方法.
Java 9 添加了Optional.or\xe2\x80\x8b(supplier)针对这种情况的方法。
return firstChoice().or(this::secondChoice);\nRun Code Online (Sandbox Code Playgroud)\n给定方法firstChoice()和secondChoice()其中每个 return Optional<Foo>,上面的一行使用Optional.or来实现所需的结果。
根据需要,此方法仅计算secondChoice何时firstChoice为空。
您只需将其替换为,
Optional<Foo> firstChoice = firstChoice();
return firstChoice.isPresent()? firstChoice : secondChoice();
Run Code Online (Sandbox Code Playgroud)
除非firstChoice.isPresent()为false,否则上述代码不会调用.
但是你必须准备调用这两个函数来获得所需的输出.没有其他方法可以逃避检查.
也许是这样的:
Optional<String> finalChoice = Optional.ofNullable(firstChoice()
.orElseGet(() -> secondChoice()
.orElseGet(() -> null)));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15688 次 |
| 最近记录: |