1. Introduction
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 Collection
extends Iterable
interface.
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 collect(Collectors.toList())
method.
In the first approach we could also use other methods to iterate over Iterable object:
Using for
statement:
or using while
:
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 Lists.newArrayList()
method:
Guava just like Apache Commons allows us to simplify conversion into a single line of code.
6. Conclusion
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}