Convert an Iterator to a List in Java

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

 

1. Naive

Simple solution is to create an empty list, and add each remaining element of the iterator to that list.

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

2. Converting the iterator to an iterable

The idea here is to convert the iterator to an iterable which can be easily done by using lamdba in Java 8. Then we convert the iterable to Stream by using StreamSupport.stream() method. Finally, we get a List from the Stream using a Collector.

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

3. Using Guava

Guava library provides several utility methods to get a mutable or an immutable list from an iterator, as shown below:

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]
[A, B, C]

 

4. Using Apache Commons Collections

Similar to Guava Library, Apache Commons Collections also provides static utility methods and decorators for Iterator instances. To serve our purpose, we can use IteratorUtils.toList() method to get a list based on an iterator.

 

Download

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