How to convert Iterable to Collection

In this tutorial we will check java solutions of conversion Iterable to Collection.

Java solutions

1. for loop

Simple solution that iterates over the elements and adds them into the collection one by one:

List<T> list = new ArrayList<T>();
for (T element: iterable) {
    list.add(element);
}

2. while loop

In this case we use directly the iterator’s methods (hasNext and get) to control iteration over the elements:

List<T> list = new ArrayList<T>();
while (iterator.hasNext()) {
list.add(iterator.next());
}

3. foreach

The Java 8 foreach method:

List<T> list = new ArrayList<>();
iterable.forEach(list::add);

4. streams

Example with the use of the Java 8 streams:

StreamSupport.stream(iterable.spliterator(), false)
.collect(Collectors.toList());

Third party libraries

5. Guava

Using the Guava library there are many possibilities:

List<T> list = Lists.newArrayList(iterable);
List<T> list = ImmutableList.copyOf(iterable);
List<T> list = Lists.newArrayList(iterable);

6. Apache Commons

Another utility library that provides many utility methods:

List<T> list = IterableUtils.toList(iterable);
List<T> list = IterableUtils.toList(iterator);

Summary

As we see, there many possibiliteies to convert Iterable (or Iterator) into the Collection. The choice depends on us whether we choose the utility library like Guava or plain Java solution.

Leave a Reply

Your email address will not be published. Required fields are marked *