Tapas Bose Tapas Bose - 1 year ago 244
Java Question

Break or return from Java 8 stream forEach?

When using external iteration over an

we use
from enhanced for-each loop as:

for (SomeObject obj : someObjects) {
if (some_condition_met) {
break; // or return obj

How can we
using the internal iteration in a Java 8 lambda expression like:

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

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download