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

4万+

被折叠的 条评论
为什么被折叠?



