Convert an Iterable to a Collection in Java

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

 

1. Naive

Naive solution would be to write our own utility method as shown below.

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

We know that for-each loop uses an iterator behind the scenes. We can also use the Iterators as shown below:

 

Download   Run Code

 
In java 8 and above, we can do something like:

 

Download   Run Code

 

2. Java 8 – Stream

Another solution is to use Streams in Java 8. The idea is to convert the iterable to Spliterator first. Then we can easily get a stream from spliterator using StreamSupport.stream() method. Finally, we collect values from the Stream into an List using Collectors.

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

3. Guava

We can also use Lists.newArrayList() or ImmutableList.copyOf() methods provided by Guava that takes an Iterable and returns a mutable or immutable List respectively.

To get an Set instead, we can use Sets.newHashSet() or ImmutableSet.copyOf() method.

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

We can also change the iterable to be a FluentIterable and then make a call to FluentIterable.toList(). This can be used with Java 7 or before (before introduction of the Stream library in Java 8).

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

4. Apache Commons Collections

Apache Commons Collections IteratorUtils class also provides many static utility methods and decorators for Iterator instances. We can use toList() method the takes an iterator and returns a List.

 

Download

Output:

[1, 2, 3, 4, 5]

 
Another approach is to use CollectionUtils.addAll() method as shown below:

 

Download

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