Tapas Bose Tapas Bose - 7 months ago 1360
Java Question

How to break or return from Java8 Lambda forEach?

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 Java8 Lambda expression like:

someObjects.forEach(obj -> {
//what to do here?
})

Answer

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