This post will discuss the groupingBy() method provided by the Collectors class in Java.

The groupingBy(classifier) returns a Collector implementing a “group by” operation on input elements, grouping elements according to a classification function, and returning the results in a map. Following are some examples demonstrating the usage of this function:

1. Split a list into two sublists

Download  Run Code

Output:

{false=[1, 2, 3], true=[4, 5]}
The first sublist is [1, 2, 3]
The second sublist is [4, 5]

 
This is equivalent to:

Download  Run Code

Output:

{false=[1, 2, 3], true=[4, 5]}
The first sublist is [1, 2, 3]
The second sublist is [4, 5]

2. Group students by grades

Download  Run Code

Output:

Students with A grade are [John, Joe]
Students with E grade are [Jason]
Students with A+ grade are [Tom, Lisa]

 
The groupingBy(classifier, downstream) collector allows the collection of stream elements into a map by grouping elements according to a classifier method and then performing a reduction operation on the values associated with a given key using the specified downstream Collector. Following are some examples demonstrating the usage of this function:

1. Compute average marks of students with the same grades

Download  Run Code

Output:

Students with A grade have average marks of 82.5
Students with E grade have average marks of 35.0
Students with A+ grade have average marks of 94.0

2. Count the occurrences of elements in a stream

We can also use the Collectors.groupingBy() method to count the frequency of elements present in a stream.

Download  Run Code

Output:

{A=3, B=1, C=2}

 
This is equivalent to:

Download  Run Code

Output:

{A=3, B=1, C=2}

That’s all about the Collectors class groupingBy() method in Java.