Collectors: Grouping Operations

Grouping operations

Grouping operations are one of the most important features of streams because they can help you complete a task, which otherwise would have taken a lot of coding, in just 2-3 lines of code.

Let’s say, for example, we have a list of Employee objects. We need to group all our employees based on their countries of residence. Or, say we need to find the average age/salary of all employees in a particular country. These kinds of operations can be done very easily with grouping APIs provided in the Collectors class.

Let’s explore these APIs in detail.

1) Collectors.groupingBy()

This method groups the input elements according to the supplied classifier and returns the results in a Map.

This method is similar to the group by clause of SQL, which can group data on some parameters.

There are three overloaded versions of this method. We will discuss each one of them.

a) groupingBy(Function<? super T, ? extends K> classifier)

This method takes only an instance of a Function interface as a parameter.

In the below example, we use groupingby() to group the Employee objects based on countries of residence.

Get hands-on with 1400+ tech skills courses.