Convert an Iterator to Iterable in Java
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>.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Arrays; import java.util.Iterator; // Program to convert an iterator to Iterable in Java class Main { public static<T> Iterable<T> iteratorToIterable(Iterator<T> iterator) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return iterator; } }; } public static void main(String[] args) { Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5).iterator(); Iterable<Integer> iterable = iteratorToIterable(iterator); iterable.forEach(System.out::println); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Arrays; import java.util.Iterator; class Main { public static<T> Iterable<T> iteratorToIterable(Iterator<T> iterator) { return () -> iterator; } public static void main(String[] args) { Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5).iterator(); Iterable<Integer> iterable = iteratorToIterable(iterator); iterable.forEach(System.out::println); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.Arrays; import java.util.Iterator; import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.StreamSupport; // Program to convert an iterator to Iterable in Java class Main { private static <T> Iterable<T> iteratorToIterable(Iterator<T> iterator) { // 1. Convert the Iterator into a Spliterator // 2. Convert the Spliterator into a sequential stream // 3. Convert the Stream to an Iterable return StreamSupport .stream(Spliterators.spliteratorUnknownSize(iterator, 0), false) .collect(Collectors.toList()); } public static void main(String[] args) { Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5).iterator(); Iterable<Integer> iterable = iteratorToIterable(iterator); iterable.forEach(System.out::println); } } |
Output:
1
2
3
4
5
That’s all about converting an Iterator to Iterable in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)