Multi level grouping with streams

1 Introduction

With Java 8 streams it is pretty easy to group collections of objects based on different criteria. In this post, we will see how we can make stream grouping, from simple single level groupings to more complex, involving several levels of groupings.

We will use two classes to represent the objects we want to group by: person and pet.





In the main method we create the collection we will use in the following sections.


You can take a look at the source code at my Github repository.

2 Single level grouping

The simplest form of grouping is the single level grouping. In this example we are going to group all persons in the collection by their country:


If we take a look into the map, we can see how each country contains a list of its citizens:

stream grouping - single level


The result shows persons living in the specified country:

Persons in USA: [Person{name=’John’, country=’USA’, city=’New York’}, Person{name=’Anna’, country=’USA’, city=’New York’}, Person{name=’Mike’, country=’USA’, city=’Chicago’}]

3 Two level grouping

In this example, we will group not only by country but also by city. To accomplish this, we need to implement a two level grouping. We will group persons by country and for each country, we will group its persons by the city where they live.

In order to allow multi level grouping, the groupingBy method in class Collectors supports an additional Collector as a second argument:

Let’s use this method to implement our two level grouping:


If we debug the execution, we will see how people is distributed:

stream grouping - two level

4 Three level grouping

In our final example, we will take a step further and group people by country, city and pet name. I have split it into two methods for readability:


Now we have three nested maps containing each list of persons:

stream grouping - three level


5 Conclusion

The Java 8 Collectors API provides us with an easy way to group our collections. By nesting collectors, we can add different layers of groups to implement multi level groupings.

I’m publishing my new posts on Google plus and Twitter. Follow me if you want to be updated with new content.


Share it:

Leave a Reply

Your email address will not be published. Required fields are marked *