I was trying to stop forEach
after a certain condition is met by closing the stream, so I did the following
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
stream.forEach((e) -> {
System.out.println("inside for Each");
if(e == 3) {
stream.close();
} else {
System.out.println(e);
}
});
I was expecting the following output:
inside for Each
1
inside for Each
2
inside for Each
but I got the following output:
inside for Each
1
inside for Each
2
inside for Each
inside for Each
4
inside for Each
5
which means that the forEach
continued after closing the stream... it didn't even throw an exception about accessing an element after the stream is closed. Any explanation for that output?