组合可选项的最优雅方法是什么? [英] What's the most elegant way to combine optionals?

查看:83
本文介绍了组合可选项的最优雅方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是到目前为止我得到的:

Here's what I've got so far:

Optional<Foo> firstChoice = firstChoice();
Optional<Foo> secondChoice = secondChoice();
return Optional.ofNullable(firstChoice.orElse(secondChoice.orElse(null)));

这让我感到既丑陋又浪费.如果存在firstChoice,则我将不必要地计算secondChoice.

This strikes me as both hideous and wasteful. If firstChoice is present I am needlessly computing secondChoice.

还有一个更有效的版本:

There's also a more efficient version:

Optional<Foo> firstChoice = firstChoice();
if(firstChoice.isPresent()) {
 return firstChoice;
} else {
 return secondChoice();
}

在这里,我不能在不复制映射器或声明另一个局部变量的情况下将某些映射函数链接到最后.所有这些使代码比要解决的实际问题更加复杂.

Here I can't chain some mapping function to the end without either duplicating the mapper or declaring another local variable. All of this makes the code more complicated than the actual problem being solved.

我宁愿这样写:

return firstChoice().alternatively(secondChoice());

但是,可选的:::显然不存在.现在呢?

However Optional::alternatively obviously doesn't exist. Now what?

推荐答案

尝试一下:

firstChoice().map(Optional::of)
             .orElseGet(this::secondChoice);

map方法为您提供Optional<Optional<Foo>>.然后,orElseGet方法将其变平为Optional<Foo>.仅当firstChoice()返回空的可选内容时,才会评估secondChoice方法.

The map method gives you an Optional<Optional<Foo>>. Then, the orElseGet method flattens this back to an Optional<Foo>. The secondChoice method will only be evaluated if firstChoice() returns the empty optional.

这篇关于组合可选项的最优雅方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆