break or continue java 8 stream lambda foreach(loop)

本文介绍如何利用 Java 8 的 Streams API 来优化集合操作,包括如何使用 filter 和 findFirst 方法快速查找符合条件的第一个元素,以及使用 anyMatch 方法判断集合中是否存在满足条件的元素。这些方法相较于传统的 forEach 循环提供了更高效且简洁的解决方案。

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<SomeObject> 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);

http://blog.csdn.net/lmy86263/article/details/51057733

http://stackoverflow.com/questions/23996454/terminate-or-break-java-8-stream-loop

http://stackoverflow.com/questions/23308193/how-to-break-or-return-from-java8-lambda-foreach

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值