Counting Elements with Collectors.counting()
You'll learn how Collectors.counting() provides a readable way to count stream elements when used as a downstream collector.
Why Collectors.counting() Exists
You already know the count() terminal operation counts all elements in a stream. But what if you want to count elements within groups or partitions? That's where Collectors.counting() shines—it's designed to work as a downstream collector with operations like groupingBy() and partitioningBy().
Think of it like this: count() is for counting the whole basket of apples, while Collectors.counting() is for counting apples within each color group when you've already sorted them.
Basic Usage
When used alone with collect(), counting() is equivalent to count():
List<String> names = List.of("Alice", "Bob", "Charlie");
// Using count() terminal operation
long countA = names.stream().count(); // 3
// Using Collectors.counting()
Long countB = names.stream().collect(Collectors.counting()); // 3
Notice counting() returns a Long object, not a primitive long.
Real Power: Downstream Counting
The true value emerges when counting within groups:
List<String> words = List.of("cat", "dog", "bird", "cow", "eagle");
Map<Integer, Long> countByLength = words.stream()
.collect(Collectors.groupingBy(
String::length,
Collectors.counting()
));
// Result: {3=2, 4=2, 5=1}
// Two words with 3 letters, two with 4, one with 5
Here, counting() acts as the downstream collector, counting how many words fall into each length category.
Key Takeaway: Use Collectors.counting() as a downstream collector with groupingBy() or partitioningBy() to count elements within each category, making your code more expressive than manual counting.