How to create a stream from an iterator in java 8

H

Hi guys!

In this post I’ll show you how to convert a java iterator to a java 8 stream. The code is really simple:

public static <T> Stream<T> iteratorToStream(final Iterator<T> iterator, final boolean parallell) {
    Iterable<T> iterable = () -> iterator;
    return StreamSupport.stream(iterable.spliterator(), parallell);
}

Just copy paste this static method in any class you like. It’s generic so you can use this method for all types of iterators. Enjoy!

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Tag Cloud

Categories