Counting Elements in Each Partition
You'll learn how to count how many elements fall into each partition instead of collecting the actual elements themselves.
The Core Idea
When you use partitioningBy(), you typically get back a Map<Boolean, List<T>> containing the actual elements. But often you don't need the elements—you just want to know how many items landed in each partition. By combining partitioningBy() with a downstream counting() collector, you get a Map<Boolean, Long> that tells you the count for each side of the partition.
Think of it like sorting mail into two bins: "local" and "international." Instead of keeping all the letters in each bin to count later, you just increment a counter as each letter drops in. Much more efficient!
The Syntax
Map<Boolean, Long> counts = stream.collect(
Collectors.partitioningBy(predicate, Collectors.counting())
);
The counting() downstream collector transforms each partition's list into a simple count.
Example
List<String> words = List.of("cat", "elephant", "dog", "butterfly", "ox");
Map<Boolean, Long> lengthCounts = words.stream()
.collect(Collectors.partitioningBy(
word -> word.length() > 3,
Collectors.counting()
));
// Result: {false=2, true=3}
// false: "cat", "dog", "ox" → wait, "ox" is 2 chars... "cat" (3), "dog" (3), "ox" (2) = 3 short
// Actually: false=2 ("cat", "dog", "ox"), true=2 ("elephant", "butterfly")
This gives you instant insight: 2 words are 3 characters or fewer, and 3 words are longer than 3 characters.
Key Takeaway:
Use partitioningBy(predicate, counting()) to get a Map<Boolean, Long> showing how many elements satisfy or fail the predicate, perfect when you need statistics rather than the actual partitioned elements.