Saturday, October 28, 2023

A Sip of Java: Maps from collections of objects using Collectors (groupingBy and partitioningBy)

 We can use streams and collectors to get Maps from a collection of objects. These Maps could be the result of our collection grouped or partitioned in specific ways.

Let's say we have a collection of Employees, where an Employee has attributes like: name, years of experience, tenure (in the company), role name, experience level.

Now let's say we want to group our employees by the experience level:

What if we dont need to know the employees with some experience level but the total number of employees with that experience level?:

In this case we are using the version of the method Collectors.groupingBy that uses another Collector as downstream collector.

Ok, what if then, we have to partition the collection based on some condition that could be true or false? In that case we use Collectors.partitioningBy:

Collectors.partitioningBy method also has a version that receives another Collector as downstream collector where we can execute other interesting logic, like grouping the result.