Java 8中的链接选项 [英] Chaining Optionals in Java 8

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

问题描述

寻找一种链接选项的方法,以便返回第一个存在的选项。如果不存在应该返回Optional.empty()

Looking for a way to chain optionals so that the first one that is present is returned. If none are present Optional.empty() should be returned.

假设我有几个这样的方法:

Assuming I have several methods like this:

Optional<String> find1()

我正在尝试将它们链接起来:

I'm trying to chain them:

Optional<String> result = find1().orElse( this::find2 ).orElse( this::find3 );

但当然这不起作用,因为 orElse 期望值和 orElseGet 期望供应商

but of course that doesn't work because orElse expects a value and orElseGet expects a Supplier.

推荐答案

使用流:

Stream.of(find1(), find2(), find3())
    .filter(Optional::isPresent)
    .map(Optional::get)
    .findFirst();

如果您需要懒惰地评估查找方法,请使用供应商函数:

If you need to evaluate the find methods lazily, use supplier functions:

Stream.of(this::find1, this::find2, this::find3)
    .map(Supplier::get)
    .filter(Optional::isPresent)
    .map(Optional::get)
    .findFirst();

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

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