Handling Empty Partitions
What you'll learn: You'll discover that partitioningBy() guarantees both true and false keys always exist in the result map, even when no elements match one of the partitions.
The Safety Net of Partitioning
Unlike groupingBy(), which only creates map entries for groups that actually contain elements, partitioningBy() follows a different rule: both boolean keys are always present. Even if all elements go into one partition, the other partition will exist as an empty list.
Think of it like two sorting bins labeled "Yes" and "No"—the bins themselves are always there, even if one remains empty. This behavior eliminates null-pointer risks when accessing partitions.
Why This Matters
When you partition a stream, you can confidently access both map.get(true) and map.get(false) without checking if the keys exist. Both will return a List, though one might be empty.
Consider partitioning numbers by whether they're even:
List<Integer> numbers = List.of(2, 4, 6, 8);
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
// Both keys exist!
List<Integer> evens = partitioned.get(true); // [2, 4, 6, 8]
List<Integer> odds = partitioned.get(false); // [] empty, but not null
Even though there are no odd numbers, the false key maps to an empty list. You can safely call methods like odds.size() or odds.isEmpty() without null checks.
The Guarantee
This design choice makes partitioning predictable and safe. The result map always has exactly two entries, no more, no less. This is different from groupingBy(), where the number of entries depends on how many distinct groups your data produces.
Key Takeaway: partitioningBy() always produces a map with both true and false keys, mapping to empty lists when a partition has no matching elements—making your code safer and more predictable.