Java 8 中的链式可选项 [英] Chaining Optionals in Java 8
本文介绍了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()
我正在尝试链接它们:
Optional<String> result = find1().orElse( this::find2 ).orElse( this::find3 );
但这当然不起作用,因为 orElse
需要一个值,而 orElseGet
需要一个 Supplier
.
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();
如果您需要懒惰地评估 find 方法,请使用供应商函数:
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屋!
查看全文