How to read a stream one by one?

The Java function Stream.forEachhas a serious limitation that prevents its consumer from throwing checked exceptions. Thus, I would like to access the Stream elements one at a time.

I want to do something like this:

while(true) {
    Optional<String> optNewString = myStream.findAny();

    if (optNewString.isPresent())
        doStuff(optNewString.get());
    else
        break;
}

However, it findAnyis a short-circuited terminal operation. That is, it closes the stream. This code will fail on the second iteration of the while loop. I can't just put all the elements inside the array and go through this array one by one, because there are potentially tens of millions of elements.

Please note that I am not asking how to make exceptions to forEach. This question has already been received.

+6
1

, iterator():

Iterator<String> iterator = stream.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
    // Use element
}

, , , - , , , - , .

+11

All Articles