Collectors introduced in Java 8 provide a powerful mechanism for working with Java streams. In this short tutorial we will look at how to use a collector to collect the items from a stream to an immutable collection.
To save time we will use the excellent Google Guava library which provides support for immutable collections. We will install the Guava library as a maven dependency.
1 2 3 4 5 | <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
|
Now let’s write some code to complete our task. From Guava version 21.0 each immutable collection in the Guava library comes with a corresponding collector. We can take advantage of this combination to complete our task.
1 2 3 4 5 6 7 8 9 10 | @Test
public void toImmutableList() {
List<Integer> listOfIntegers = List.of(1, 2, 3, 4, 4, 5);
List<Integer> immutableList = listOfIntegers
.stream()
.collect(ImmutableList.toImmutableList());
assertThat(listOfIntegers, is(immutableList));
}
|
In the above code we use the stream collect method and pass an immutable list collector from the Guava library.
1 | ImmutableList.toImmutableList()
|
This collector collects the elements of the stream into an immutable list.
In this tutorial we looked at how to collect the elements of a stream into an immutable list. We used the excellent Guava library that provided us with immutable collections and collectors to perform this task.