Java 中的可选 orElse 可选 [英] Optional orElse Optional in Java

查看:34
本文介绍了Java 中的可选 orElse 可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用新的可选类型在 Java 8 中,我遇到了一个看似常见但功能上不受支持的操作:orElseOptional"

I've been working with the new Optional type in Java 8, and I've come across what seems like a common operation that isn't supported functionally: an "orElseOptional"

考虑以下模式:

Optional<Result> resultFromServiceA = serviceA(args);
if (resultFromServiceA.isPresent) return result;
else {
    Optional<Result> resultFromServiceB = serviceB(args);
    if (resultFromServiceB.isPresent) return resultFromServiceB;
    else return serviceC(args);
}

这种模式有多种形式,但归根结底是想要一个可选项上的orElse",该函数接受一个函数来生成一个新的可选项,只有当当前的选项不存在时才调用.

There are many forms of this pattern, but it boils down to wanting an "orElse" on an optional that takes a function producing a new optional, called only if the current one does not exist.

它的实现看起来像这样:

It's implementation would look like this:

public Optional<T> orElse(Supplier<Optional<? extends T>> otherSupplier) {
    return value != null ? this : other.get();
}

我很好奇这样的方法不存在是否有原因,如果我只是以一种非预期的方式使用 Optional,以及人们想出了哪些其他方法来处理这种情况.

I'm curious if there's a reason such a method doesn't exist, if I'm just using Optional in an unintended way, and what other ways people have come up with to deal with this case.

我应该说,我认为涉及自定义实用程序类/方法的解决方案并不优雅,因为使用我的代码的人不一定知道它们存在.

I should say that I think that solutions involving custom utility classes/methods aren't elegant because people working with my code won't necessarily know they exist.

另外,如果有人知道,这样的方法会包含在JDK 9中吗,我在哪里可以提出这样的方法?对我来说,这似乎是 API 的一个明显遗漏.

Also, if anyone knows, will such a method be included in JDK 9, and where might I propose such a method? This seems like a pretty glaring omission to the API to me.

推荐答案

这是 JDK 9 中 or 形式的一部分,它采用 Supplier>.您的示例将是:

This is part of JDK 9 in the form of or, which takes a Supplier<Optional<T>>. Your example would then be:

return serviceA(args)
    .or(() -> serviceB(args))
    .or(() -> serviceC(args));

详情参见Javadoc这篇文章 我写的.

For details see the Javadoc or this post I wrote.

这篇关于Java 中的可选 orElse 可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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