Convert an Iterator to Iterable in Java

In this post, we will see how to convert an Iterator to Iterable in Java.

 

1. Java 7 and before

The Iterable interface declares a single abstract method iterator() that returns a Iterator<T>.

 

Download   Run Code

Output:

1
2
3
4
5

 

2. Java 8 and above

The Iterable is effectively a functional Interface and converting an Iterator to Iterable can be done very easily with a lambda expression in Java 8 and above as shown below:

 

Download   Run Code

Output:

1
2
3
4
5

 

3. Converting Iterator to Spliterators

 
The idea is to convert the iterator into a Spliterator using Spliterators.spliteratorUnknownSize() and then create a new sequential Stream from Spliterator by using StreamSupport.stream() method. Finally, we convert the stream to an iterable using a Collector.

 

Download   Run Code

Output:

1
2
3
4
5

 
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