我有一个id
值可以是null
。然后我需要用这个调用一些服务id
获取交易列表并获取第一个不null
从列表中进行交易。
目前我有这个工作代码
Optional.ofNullable(id)
.map(id -> service.findTrades(id))
.flatMap(t -> t.stream().filter(Objects::nonNull).findFirst())
.orElse(... default value...);
是否可以实现一条线flatMap
打电话更优雅?我不想在一个管道步骤中加入太多逻辑。
最初我希望以这种方式实现逻辑
Optional.ofNullable(id)
.flatMap(id -> service.findTrades(id))
.filter(Objects::nonNull)
.findFirst()
.orElse(... default value...);
But Optional.flatMap
不允许将列表展平为一组元素。
我不知道这是否优雅,但这里有一种在启动流管道之前转换流中可选值的方法:
Trade trade = Optional.ofNullable(id)
.map(service::findTrades)
.map(Collection::stream)
.orElse(Stream.empty()) // or orElseGet(Stream::empty)
.filter(Objects::nonNull)
.findFirst()
.orElse(... default value...);
在Java 9中,Optional将有一个.stream() method http://download.java.net/java/jdk9/docs/api/java/util/Optional.html#stream--,因此您将能够直接将可选内容转换为流:
Trade trade = Optional.ofNullable(id)
.stream() // <-- Stream either empty or with the id
.map(service::findTrades) // <-- Now we are at the stream pipeline
.flatMap(Collection::stream) // We need to flatmap, so that we
.filter(Objects::nonNull) // stream the elements of the collection
.findFirst()
.orElse(... default value...);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)