Java – how to read streams one by one?

Java Stream. The foreach function has a serious limitation that its consumer cannot throw a checked exception Therefore, I want to access the elements of the stream 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 circuit terminal operation That is, it closes the flow This code will crash at the second iteration of the while loop I can't simply put all the elements in an array and traverse the array one by one, because there may be tens of millions of elements

Please note that I am not asking how to throw an exception from foreach This question has already been answered

Solution

To iterate the flow element by element, simply call the iterator () method:

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

It's not clear how helpful it is in checking exceptions. It's worth noting that it's a terminal operation - once you use an iterator, you need to get a new stream if you want to iterate again - but it does answer the question of how to read one element at a time

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>