This post will discuss how to convert an iterator to Iterable in Java.

1. Java 7

The Iterable interface declares a single abstract method iterator() that returns an 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 an 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 the StreamSupport.stream() method. Finally, we convert the stream to an iterable using a Collector.

Download  Run Code

Output:

1
2
3
4
5

That’s all about converting an Iterator to Iterable in Java.