Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break or return from Java 8 stream 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 a Java 8 lambda expression like:

someObjects.forEach(obj -> {    //what to do here? }) 
like image 752
Tapas Bose Avatar asked Apr 26 '14 07:04

Tapas Bose


People also ask

Can we use break in forEach Java 8?

You can't. Just use a real for statement.

Can I use break in forEach Java?

break from loop is not supported by forEach. If you want to break out of forEach loop, you need to throw Exception.

Which is better stream or forEach in Java?

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.


1 Answers

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); 
like image 172
Jesper Avatar answered Sep 21 '22 17:09

Jesper