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? })
You can't. Just use a real for statement.
break from loop is not supported by forEach. If you want to break out of forEach loop, you need to throw Exception.
Performance. There are many opinions about which style performs better. The short version basically is, if you have a small list; for loops perform better, if you have a huge list; a parallel stream will perform better.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With