The Java Stream.forEach
function has the serious limitation that it's impossible for its consumer to throw checked exceptions. As such, I would like to access a Stream's elements one by one.
I want to do something like this:
while(true) {
Optional<String> optNewString = myStream.findAny();
if (optNewString.isPresent())
doStuff(optNewString.get());
else
break;
}
However, findAny
is a short-circuiting terminal operation. That is, it closes the stream. This code would crash on the second iteration of the while loop. I cannot simply put all elements inside an array, and go over that array one by one, because there are potentially tens of millions of elements.
Please note I am not asking how to throw exceptions from within forEach
. This question has already been answered.