Intellipaat 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
asked Feb 15, 2020 in BI by angadmishra (6.5k points)
0 votes
1 answer
0 votes
1 answer
asked Nov 24, 2019 in Java by Anvi (10.2k points)

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...