这是我到目前为止
Optional firstChoice = firstChoice();
Optional secondChoice = secondChoice();
return Optional.ofNullable(firstChoice.orElse(secondChoice.orElse(null)));
这对我来说是可怕的和浪费的。如果firstChoice存在,我不必要地计算secondChoice。
还有一个更有效的版本:
Optional firstChoice = firstChoice();
if(firstChoice.isPresent()) {
return firstChoice;
} else {
return secondChoice();
}
在这里,我无法将一些映射函数链接到最后,而无需复制映射器或声明另一个局部变量。所有这些使得代码比实际的问题解决更复杂。
我宁愿写这个:
return firstChoice().alternatively(secondChoice());
但可选::或者显然不存在。怎么办?