Count Occurrences Using Java GroupingBy Collector

06 May 2023 Balmiki Mandal 0 Core Java

Using Java groupingBy Collector to Count Occurrences

Java 8 introduces the groupingBy Collector, a powerful utility for counting occurrences of objects in the Stream API. The groupingBy Collector provides an easy way to group items in a Collection according to some criteria and then count occurrences within each group.

Example

Let’s consider a simple example of counting occurrences of numbers in a stream. We can create a stream of integers and then use the groupingBy Collector to count the number of times each number occurs:

Stream<Integer> numStream = Stream.of(1, 2, 3, 2, 4, 2, 5);
Map<Integer, Long> numCounts = 
     numStream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(numCounts);

This code produces the following output:

{1=1, 2=3, 3=1, 4=1, 5=1}

As you can see, the groupingBy Collector has produced a Map containing the number as the key, and the number of occurrences as the value.

Conclusion

The groupingBy Collector is a powerful tool for counting occurrences of objects in a Collection. It provides a simple way to group items in a stream according to some criteria and then count occurrences within each group.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.