java怎么中断流,从Java 8流中断或返回每个?

Java 8 流与内部迭代:如何优雅地使用 break 和 return
这篇博客探讨了在Java 8中使用流(Stream)进行内部迭代时,如何替代传统的外部迭代中用到的`break`或`return`。文章指出,如果需要中断或返回,不应使用`forEach`,而应选择其他流操作,如`filter`结合`findFirst`来找到第一个满足条件的元素,或者使用`anyMatch`来检查集合中是否存在符合条件的元素。这种方式利用了流的惰性求值特性,避免了遍历整个集合。

When using external iteration over an Iterable we use break or return from enhanced for-each loop as:

for (SomeObject obj : someObjects) {

if (some_condition_met) {

break; // or return obj

}

}

How can we break or return using the internal iteration in a Java 8 lambda expression like:

someObjects.forEach(obj -> {

//what to do here?

})

解决方案

If you need this, you shouldn't use forEach, but one of the other methods available on streams; which one, depends on what your goal is.

For example, if the goal of this loop is to find the first element which matches some predicate:

Optional result =

someObjects.stream().filter(obj -> some_condition_met).findFirst();

(Note: This will not iterate the whole collection, because streams are lazily evaluated - it will stop at the first object that matches the condition).

If you just want to know if there's an element in the collection for which the condition is true, you could use anyMatch:

boolean result = someObjects.stream().anyMatch(obj -> some_condition_met);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值