牛骨文教育服务平台(让学习变的简单)
博文笔记

break or continue java 8 stream lambda foreach(loop)

创建时间:2016-10-21 投稿人: 浏览次数:1738

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

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。