In this article we will present several ways to convert Iterable object to a Collection in Java, using plain Java solution, and external libraries such as Apache Commons or Guava. Iterable is an interface that allows an object to be the target of the "for-each loop" statement.
2. Sample list
Let's start with creating a sample list of objects:
We could assign
Arrays.asList(...) result to the
Iterable because in Java every
3. Convert Iterable to Collection using plain Java
In plain Java, we could use several approaches to convert Iterable into Collection.
We could make use of the
forEach(...) statement to iterate over our object and assign each value into another list.
Another solution is to use
StreamSupport.stream(...) that converts the
Iterable object into a
Stream. That stream could be dropped to the list using
In the first approach we could also use other methods to iterate over Iterable object:
4. Iterable to Collection using Apache Commons library
We could use libraries such as Apache Commons Collections that provide helper methods to convert objects:
In this example, we used the
IterableUtils.toList(...) method gives us a simple and single-line solution.
5. Convert Iterable to Collection using Guava
The Guava library also provides helper methods to convert Iterable objects into Collections.
To create a list from
Iterable instance we used
Guava just like Apache Commons allows us to simplify conversion into a single line of code.
In this tutorial, we presented ways to convert an Iterable to a Collection object in Java. We presented solutions using plain Java, and two libraries: Guava and Apache Commons Collections.
As usual, the code used in this tutorial is available on our GitHub.