Create a Sequential Stream from an Iterator in Java

In this post, we will see how to create a sequential Stream from an Iterator in Java.

 

1. Using Spliterators

Creating a sequential Stream from an Iterator is a 2-step process in Java. The first step involves converting the Iterator into a Spliterator and in second step we turn that Spliterator into a Stream.

We can use Spliterators.spliteratorUnknownSize() method to create a Spliterator from a given Iterator as the source of elements, and then call StreamSupport.stream() to create a new sequential or parallel Stream from Spliterator as shown below:

 

Download   Run Code

Output:

[A, B, C, D]

 

2. Using an Iterable

Another option is to use an Iterable as Iterable interface provides spliterator() method that creates a Spliterator over the elements described by the Iterable.

Since Iterable interface declares a single abstract method iterator() that returns a Iterator<T>, this makes Iterable effectively a FunctionalInterface and creating an Iterable from an Iterator can be done very easily by using a lambda as shown below:

 

Download   Run Code

Output:

[A, B, C, D]

 

Please note that Iterable.spliterator() itself internally uses Spliterators.spliteratorUnknownSize() method to get a Spliterator over the elements described by the Iterable.

 

3. Guava library

Guava library introduced Streams class in version 21.0, which has stream() method that returns a sequential Stream of the remaining contents of iterator.

Please note that this method also internally calls Spliterators.spliteratorUnknownSize() to convert the Iterator to a Spliterator and StreamSupport.stream() to get a sequential Stream from Spliterator.

 

Download   Run Code

Output:

[A, B, C, D]

 

4. Stream.generate()

The simplest solution is to use Stream.generate(iterator::next). But this will only work with infinite Streams and throw NoSuchElementException with finite Streams. This is because Iterator.hasNext() is never called to determine if the iteration has more elements.

 

Download   Run Code

Output:

0
1
2
3
4
5
.
.
.
[infinity]

 

We can also use this with finite Streams if we know the number of elements n in the Stream in advance. Now we can limit the Stream as shown below:

 

Download   Run Code

Output:

[A, B, C, D]

 

Please note that after getting a Stream of the elements from a iterator, the Stream should be consumed immediately. Since streams are lazy in Java, it is linked only to an iterator but if the iterator is used before calling a terminal operation on the Stream, the stream would be left with only remaining items.

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz