Collectors groupingBy() method in Java

In this post, we will discuss groupingBy() method provided by 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.

 

Example #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]

 

Example #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 function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

 

Example #1: Compute average marks of students with 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

 

Example #2: Count the occurrences of elements in a Stream

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

 

Download   Run Code

Output:

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

 

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of