java for循环迭代_如何使用Java 8流迭代嵌套for循环引用父元素?

当您需要两个值并且想要使用flatMap时(根据需要执行像findFirst这样的短路操作时),您必须映射到包含两个值的对象

response.getFirstNodes().stream()

.flatMap(first->first.getSndNodes().stream()

.map(snd->new AbstractMap.SimpleImmutableEntry<>(first,snd)))

.filter(e->e.getValue().isValid())

.findFirst().ifPresent(e-> {

result.setKey(e.getKey().getKey());

result.setContent(e.getValue().getContent());

});

为了仅使用标准类,我使用Map.Entry作为Pair类型,而真正的Pair类型可能看起来更简洁.

在此特定用例中,您可以将筛选器操作移动到内部流

response.getFirstNodes().stream()

.flatMap(first->first.getSndNodes().stream()

.filter(snd->snd.isValid())

.map(snd->new AbstractMap.SimpleImmutableEntry<>(first,snd)))

.findFirst().ifPresent(e-> {

result.setKey(e.getKey().getKey());

result.setContent(e.getValue().getContent());

});

它具有整洁的效果,只有一个匹配的项目,一个Map.Entry实例将被创建(好吧,应该作为the current implementation is not as lazy as it should,但即便如此,它仍然会创建比第一个变体更少的对象).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值