In Java 8 and later versions, the Collectors class in the java.util.stream package provides various utility methods to perform reduction operations on streams. One of the powerful features of the Collectors class is the ability to group and count elements in a list or stream.

To group and count elements in a list, you can use the Collectors.groupingBy() and Collectors.counting() methods in combination. The groupingBy() method is used to create a Map where the elements are grouped based on a specific classifier, and the counting() method is used to count the occurrences of each group.

How to use the Collectors class in Java 8 to group and count elements in a list

How to use the Collectors class in Java 8 to group and count elements in a list? Share on X

Here’s an example of the usage of Collectors class to group and count elements in a list:

 

Output:

 

In the example above, we have a list of websites and our objective is to count the occurrences of each website present in the list. First, we will use the stream() method to convert the list to a stream, and then we use the collect() method along with Collectors.groupingBy() to group the elements by the website name. The second parameter to groupingBy() is Collectors.counting(), which will count the occurrences of each group. The websiteCount_map contains the result, where each website name is associated with its count in the original list. The result shows the count of each website in the list. So, what we have learnt is that by using the Collectors.groupingBy() and Collectors.counting() methods, we can easily perform grouping and counting operations on lists in Java 8 or any other later versions.

 

Learn to use Collectors() class to group and count elements in a List in Java 8..!!! Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    http://Techndeck.com deepak.rkgit@gmail.com Verma Deepak