Using Collectors.groupingBy() for Grouping Data in Java


The Collectors.groupingBy() method is useful for grouping elements of a stream by a certain property and performing aggregation operations like counting.

Source Code

List items = Arrays.asList("apple", "banana", "cherry", "apple", "banana", "cherry", "apple");
Map itemCount = items.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(itemCount); // Outputs: {apple=3, banana=2, cherry=2}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments