从一个Optional或另一个中获取价值 [英] Get value from one Optional or another

查看:89
本文介绍了从一个Optional或另一个中获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 java.util.Optional 个实例,我希望得到一个 Optional

I have two java.util.Optional instances and I want to get an Optional that either:


  • 如果它有值,则具有第一个可选值的值。

  • 具有值的值第二个可选,如果它有一个值。

  • 为空且两个都没有可选的值。

有没有直接的方法来做到这一点,即是否已经有一些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 接受的答案列出了一些替代方法来克服这个遗漏可选 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开始(变更集12885 ),你可以做到

Update: As of Java 9 (changeset 12885) you can do

firstOptional.or(() -> secondOptional);

对于Java 8,请继续阅读......

For Java 8, read on...

如果您想避免两次提及 firstOptional ,您可能需要使用

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();






如果有人偶然遇到这个问题,但有<选项的em> list ,我建议像

Optional<...> opt = optionals.stream()
                             .filter(Optional::isPresent)
                             .findFirst()
                             .orElse(Optional.empty());

这篇关于从一个Optional或另一个中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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