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

1. Naive solution

A naive solution is 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. Using Java 8 Stream

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

Download  Run Code

Output:

[1, 2, 3, 4, 5]

3. Using Guava Library

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 a set instead, we can use Sets.newHashSet() or ImmutableSet.copyOf() method.

Download 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 the introduction of the stream library in Java 8 and above).

Download Code

Output:

[1, 2, 3, 4, 5]

4. Using Apache Commons Collections

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

Download Code

Output:

[1, 2, 3, 4, 5]

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

Download Code

Output:

[1, 2, 3, 4, 5]

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