Breaking or Returning from Java 8 Stream forEach
Like external iteration using enhanced for-each loops, internal iteration with Java 8 lambda expressions requires a different approach for breaking or returning. Breaking out of a for-each loop can be accomplished using the break statement or by returning the current object.
In the case of stream forEach, neither break nor return can be used. The reason for this is that forEach is a terminal operation, meaning it executes a side-effect on each element and does not return any value.
Alternatives for Breaking or Returning from Stream forEach
Instead, one should consider using other stream methods that offer different functionality:
Example Code
Using filter() to find the first element that satisfies a condition:
<code class="java">Optional<SomeObject> result = someObjects.stream().filter(obj -> some_condition_met).findFirst();</code>
Using anyMatch() to determine if any element meets a predicate:
<code class="java">boolean result = someObjects.stream().anyMatch(obj -> some_condition_met);</code>
The above is the detailed content of How to Break or Return from Java 8 Stream forEachLike Iteration?. For more information, please follow other related articles on the PHP Chinese website!