展平Java 8可选管道中的元素列表 [英] Flattening a list of elements in Java 8 Optional pipeline

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

问题描述

我有一个id值,可以是null.然后,我需要使用此id调用某些服务以获取交易列表,并从该列表中获取第一个非null交易.

I have a id value which can be null. Then I need to call some service with this id to get a list of trades and fetch the first not null trade from the list.

当前我有此工作代码

Optional.ofNullable(id)
    .map(id -> service.findTrades(id))
    .flatMap(t -> t.stream().filter(Objects::nonNull).findFirst())
    .orElse(... default value...); 

是否可以更优雅地实现带有flatMap调用的行?我不想在一个流程步骤中投入太多逻辑.

Is it possible to implement a line with a flatMap call more elegantly? I don't want to put much logic in one pipeline step.

最初我希望以这种方式实现逻辑

Initially I expected to implement the logic this way

Optional.ofNullable(id)
    .flatMap(id -> service.findTrades(id))
    .filter(Objects::nonNull)
    .findFirst()
    .orElse(... default value...); 

但是Optional.flatMap不允许将列表展平为一组元素.

But Optional.flatMap doesn't allow to flatten a list into a set of it's elements.

推荐答案

我不知道这是否优雅,但这是在启动流管道之前在流中转换可选内容的一种方法:

I don't know if this is elegant or not, but here's a way to transform the optional in a stream before initiating the stream pipeline:

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中, 将具有.stream()方法,因此您将能够直接将可选内容转换为流:


In Java 9, Optional will have a .stream() method, so you will be able to directly convert the optional into a 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...); 

这篇关于展平Java 8可选管道中的元素列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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