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. However, since forEach()
is a terminal operation and is not intended to be used as a loop, it is generally better to use a different method such as findFirst()
or anyMatch()
if you only need to find a single element in the stream.
Here's an example of how you can use findFirst()
to find the first even number in a stream and return from the operation:
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 2
You can also use the anyMatch()
method to find if there is any even number in the stream and return from the operation:
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 true
I hope this helps! Let me know if you have any questions.