Introduction
In this section, we talk about the powerful Collector Interface, which allows you to build elements of a stream to a new data structure. First, we shortly cover the interface and then we talk about the basics like List, Set, and Map. Later we will go to more advanced topics like groupingBy.
If you want to play around more, I suggest using this project as starting point
Understanding the Collector Interface
The Collector Interface offers us four methods:
supplier()
: Returns a function that creates a new mutable result container.accumulator()
: Returns a function that accumulates the input element into the mutable result container.combiner()
: Returns a function that combines two mutable result containers into a single mutable result container.finisher()
: Returns a function that transforms the mutable result container into the final result.
When a Collector
is used to collect the elements of a stream, it uses these four methods to create and manipulate a mutable result container, which is then transformed into the final result.
Using Collectors
ToList and ToSet
The most basic use case for collectors is toList or toSet. Here is a short example, which will transform the stream to a new List/Set
Since Java 10, you can also do Unmodifiable Lists and Sets with the Method toList, which internally uses the Collections.unmodifiableList. Set doesn’t have yet a direct method for an unmodifiable Set, therefore you have to use Collectors.ToUnmodifiableSet
Joining
If we want to join the Strings together, we can also use the Collectors.joining method.
ToMap
We can use the Collectors.toMap()
method to collect the elements of a stream into a Map
based on a key and a value.
This code creates a Map
where the keys are the strings from the stream and the values are their lengths. The Function.identity()
method returns each string as is, and the String
GroupingBy
We can use the Collectors.toMapgroupingBy()
method to group all elements into a Map
This code creates a Map
where the keys are the first characters of the strings from the stream, and the values are lists of strings that start with that character
Pingback: Java Stream Sources – Code Nest