Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (4k points)

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?

})

1 Answer

0 votes
by (46k points)

If you require this, you shouldn't use forEach, but one of the additional methods possible on streams; which one, depends on what your goal is.

For example, if the purpose of this loop is to find the first portion which matches some word:

Optional<SomeObject> result =

    someObjects.stream().filter(obj -> some_condition_met).findFirst();

(Note: This will not iterate the whole group, because streams are lazily evaluated - it will stand at the first object that meets 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);

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.4k questions

32.5k answers

500 comments

108k users

Browse Categories

...