Introduction
This post will look at some common uses of stream groupingBy
. We will cover grouping by single and multiple fields,
counting the elements in a group and filtering on group size. We also cover some basic statistics you can use with groupingBy
.
Grouping elements in a stream
The examples in this post will use the Fruit
class you can see below. The equals
and hashCode
methods are overridden, so
two instances of the Fruit
class will be equal if they have the same name
. The toString
method is overridden to
have a more readable output in the console. The getters and setters are left out to make it more readable.
|
|
This is the list of fruits we will use for the examples.
|
|
Stream group by fields
Let's start with grouping by one field. The example below will group the fruits by their name. The result is a Map
with the fruit's name
as key and a list of fruits as the value.
|
|
If you print collect
to the console it will show the following result. First the key (the fruits name) is printed followed by the key's value a list of fruit objects.
|
|
Stream group by multiple fields
This example looks very familiar to the first example. We only added a new Collectors.groupingBy()
as the second parameter to the groupingBy
. The List is now
first grouped by the fruit's name and then by the fruit's amount.
|
|
When you print the Map
the result will look like this:
|
|
Stream group by count
We can also pass the Collectors.counting()
as a parameter to the groupingBy
. This collector will give you the number of objects inside
the group. The result of this example is a map with the fruit's name as the key and the count as the value.
|
|
When you print the Map
, you see a group for each fruit name followed by the number of fruits in that group.
|
|
Stream group by count and filter on count
We can take the previous example further by filtering on the count. To filter on the count, we need to create
a new stream of the entrySet
of the map and apply the filter we want. So in the example below, we filter out all the groups
that are smaller than two.
|
|
When you print the Map
, we see that only apple and banana have groups size of two or more.
|
|
Stream group by sum
We can also sum all the fields in a group. To do that, you need to pass the Collectors.summingInt()
to the groupingBy
.
|
|
When you print the Map
, you can see that the amount of the fruits is summed up for each group.
|
|
Stream group by and summarize (count, sum, min, avg, max)
It is also possible to get all the basic statistics when you do a groupingBy
. You only have to pass
the Collectors.summarizingInt
as the second parameter to get these statistics. There is also a summarizingDouble
and summarizingLong
.
|
|
When you print the map
you can see the count, sum, min, average, and max value for each of the groups.
|
|
Conclusion
We implemented different kinds of groupingBy
in this post. We saw how to group by one or more fields, get the size of the groups
and to get some basic statistics.