结合选项的最优雅方式是什么?

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 ::或`方法.因此可以在Java 9中编写`firstChoice().或(this :: secondChoice)`. (21认同)
  • @exception `this::secondChoice` _is_ 一个 `Supplier`。它是一个方法参考。 (2认同)
  • @exception `secondChoice()` 返回一个 `Optional`。`this::secondChoice` 是一个类型为 `Supplier&lt;Optional&lt;Foo&gt;&gt;` 的方法引用。如果你调用方法引用,你会得到`Optional`。答案中的示例适用于 Java 8 及更高版本。 (2认同)

M. *_*tin 7

Java 9 添加了Optional.or\xe2\x80\x8b(supplier)针对这种情况的方法。

\n
return firstChoice().or(this::secondChoice);\n
Run Code Online (Sandbox Code Playgroud)\n

给定方法firstChoice()secondChoice()其中每个 return Optional<Foo>,上面的一行使用Optional.or来实现所需的结果。

\n

根据需要,此方法仅计算secondChoice何时firstChoice为空。

\n


Sur*_*tta 5

您只需将其替换为,

Optional<Foo> firstChoice = firstChoice();
return firstChoice.isPresent()? firstChoice : secondChoice();
Run Code Online (Sandbox Code Playgroud)

除非firstChoice.isPresent()为false,否则上述代码不会调用.

但是你必须准备调用这两个函数来获得所需的输出.没有其他方法可以逃避检查.

  • 最好的情况是第一选择返回真实.
  • 最坏的情况是第一选择返回false,因此另一种方法调用第二选择.


Mar*_*hym 5

也许是这样的:

Optional<String> finalChoice = Optional.ofNullable(firstChoice()
    .orElseGet(() -> secondChoice()
    .orElseGet(() -> null)));
Run Code Online (Sandbox Code Playgroud)

来自:Java 8 中的链式可选项