Break or return from Java 8 stream forEach?
To break or return from a Java 8 Stream.forEach() operation, you can use the break or return statements as you would normally do in a loop.
You cannot use break or return to exit a Java 8 Stream.forEach() operation like you would in a traditional loop. The break statement is not allowed inside lambda expressions, and return only exits the lambda itself, not the surrounding stream pipeline. Because forEach() is a terminal operation designed for side effects rather than control flow, it is generally better to use short-circuiting terminal operations like findFirst(), findAny(), or anyMatch() if you need to stop processing early or check for a condition.
Here's an example of how you can use findFirst() to find the first even number in a stream:
import java.util.Arrays;
import java.util.List;
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer result = numbers.stream()
.filter(n -> n % 2 == 0)
.findFirst()
.orElse(null);
System.out.println(result); // prints 2You can also use the anyMatch() method to check if there is any even number in the stream:
import java.util.Arrays;
import java.util.List;
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
boolean result = numbers.stream()
.anyMatch(n -> n % 2 == 0);
System.out.println(result); // prints trueFor parallel streams, findAny() is often preferred over findFirst() as it allows the stream to return any matching element, which can improve performance.
I hope this helps! Let me know if you have any questions.