Combining counting() with groupingBy for Frequency Counts
You'll learn how to count how many times each distinct value appears in a stream by combining groupingBy with counting() as a downstream collector.
The Core Idea
Think of groupingBy as sorting items into labeled bins, and counting() as putting a counter on each bin. When you use counting() as the downstream collector with groupingBy, you're not just grouping elements—you're automatically tallying how many items ended up in each group.
This is the go-to pattern for frequency analysis: "How many users per country?", "How many orders per product?", or "How many occurrences of each word?"
How It Works
Instead of getting a Map<K, List<T>> (groups with their elements), you get a Map<K, Long> where each key maps directly to its count:
List<String> fruits = List.of("apple", "banana", "apple", "orange", "banana", "apple");
Map<String, Long> fruitCounts = fruits.stream()
.collect(Collectors.groupingBy(
fruit -> fruit, // classifier: group by the fruit itself
Collectors.counting() // downstream: count items in each group
));
// Result: {apple=3, banana=2, orange=1}
The counting() collector replaces the default list-collecting behavior, giving you just the numbers you need.
Real-World Example
List<Integer> grades = List.of(85, 90, 85, 78, 90, 92, 85, 78);
Map<Integer, Long> gradeFrequency = grades.stream()
.collect(Collectors.groupingBy(
grade -> grade,
Collectors.counting()
));
// Result: {78=2, 85=3, 90=2, 92=1}
Key Takeaway: Use Collectors.groupingBy(classifier, Collectors.counting()) to create a frequency map that shows how many times each distinct value appears—perfect for histograms, tallies, and distribution analysis.