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.
To iterate over a stream element-by-element, just call the iterator()
method:
Iterator<String> iterator = stream.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
// Use element
}
It's not clear to what extent that helps you in terms of checked exceptions, and it's worth noting that it's a terminal operation - once you've used the iterator, you'd need to get a new stream if you want to iterate again - but it does answer the question of how to read a stream one element at a time.
See more on this question at Stackoverflow