从一个 Optional 或另一个获取价值 [英] Get value from one Optional or another
问题描述
我有两个 java.util.Optional
实例,我想获得一个 Optional
:
I have two java.util.Optional
instances and I want to get an Optional
that either:
- 如果有值,则为第一个 Optional 的值.
- 如果有值,则为第二个 Optional 的值.
- 空的,Optional 都没有值.
是否有一种直接的方法可以做到这一点,即是否已经有一些 API 可以做到这一点?
Is there a straight-forward way to do that, i.e. is there already some API to do that?
下面的表达式会做到这一点,但我必须两次提到第一个可选:
The following expressions will do that, but I have to mention the first optional twice:
firstOptional.isPresent() ? firstOptional : secondOptional
这正是 com.google.common.base.Optional.or()
所做的,但 Java 8 的 API 中不存在该方法.
This is exactly what com.google.common.base.Optional.or()
does, but that method is not present in Java 8's API.
aioobe 接受的答案列出了一些替代方法来克服 Optional
API 的这种遗漏,其中必须计算这样的值(这回答了我的问题).我现在选择向我的代码库添加一个实用函数:
The accepted answer by aioobe lists a few alternative approaches to overcome this omission of the Optional
API right where such a value has to be computed (which answers my question). I've now opted to add a utility function to my codebase:
public static <T> Optional<T> or(Optional<T> a, Optional<T> b) {
if (a.isPresent())
return a;
else
return b;
}
推荐答案
Java 9 及更高版本:
firstOptional.or(() -> secondOptional);
Java 8 及更低版本
如果你想避免提到 firstOptional
两次,你可能不得不使用类似的东西
Java 8 and below
If you want to avoid mentioning firstOptional
twice, you'd probably have to go with something like
firstOptional.map(Optional::of).orElse(secondOptional);
或
Optional.ofNullable(firstOptional.orElse(secondOptional.orElse(null)));
但最易读的变体可能就是简单地做
But the most readable variant is probably to simply do
Optional<...> opt = firstOptional.isPresent() ? firstOptional
: secondOptional.isPresent() ? secondOptional
: Optional.empty();
<小时>
如果有人偶然发现了这个问题,但有一个列表选项,我会建议像
Optional<...> opt = optionals.stream()
.filter(Optional::isPresent)
.findFirst()
.orElse(Optional.empty());
这篇关于从一个 Optional 或另一个获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!