Break or return from Java 8 stream forEach?

foreach, java, java-8, lambda

Solution

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

Problem

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? }) ```

Original source

Related problems