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

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of