Counting Elements in Each Group
You'll learn how to count how many items fall into each category using groupingBy and counting().
The Core Idea
When you group stream elements, you often want to know how many items ended up in each group. Instead of getting the actual elements, you want a simple count per category. The Collectors.counting() downstream collector does exactly this—it counts the elements as they're grouped, producing a Map<Key, Long> where each value is the count.
Think of it like sorting mail into bins by zip code, then labeling each bin with how many letters it contains instead of keeping the actual letters.
How It Works
You combine groupingBy with counting() as the downstream collector:
Map<Category, Long> counts = stream
.collect(Collectors.groupingBy(
classifierFunction,
Collectors.counting()
));
The classifier function determines the grouping key, and counting() tallies up how many elements belong to each key.
Example
List<String> words = List.of("apple", "ant", "banana", "avocado", "berry");
Map<Character, Long> countByFirstLetter = words.stream()
.collect(Collectors.groupingBy(
word -> word.charAt(0),
Collectors.counting()
));
// Result: {a=3, b=2}
Notice the result type: Map<Character, Long>. The keys are the first letters, and the values are counts (not lists of words).
Why It's Useful
This pattern is extremely common for aggregating data: counting orders by status, users by region, errors by type, etc. It's cleaner and more efficient than grouping into lists and then measuring their sizes manually.
Key Takeaway: Use groupingBy with counting() to create a Map<Key, Long> that shows the count of elements in each group, perfect for frequency analysis and aggregation tasks.