Understanding partitioningBy and Binary Classification
You'll learn how partitioningBy provides a specialized way to split stream elements into exactly two groups based on a true/false condition.
What Is partitioningBy?
Think of partitioningBy as a security checkpoint: every element either passes (true) or fails (false), creating exactly two buckets. While groupingBy can create any number of groups based on classification keys, partitioningBy always produces a Map<Boolean, List<T>> with exactly two entries: one for true and one for false.
This is called binary classification—dividing data into two mutually exclusive categories.
Syntax and Basic Usage
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n > 10));
// Result: {false=[5, 8, 10], true=[15, 20, 11]}
The predicate n -> n > 10 tests each element. Elements satisfying the condition go into the true bucket; others go into false.
When to Use partitioningBy vs groupingBy
Use partitioningBy when:
- You have a yes/no decision (eligible/ineligible, valid/invalid)
- You need guaranteed presence of both keys (even if one list is empty)
- You're working with boolean predicates
Use groupingBy when:
- You have multiple categories (grouping by department, country, etc.)
- The number of groups is unknown or greater than two
Key Advantage: Guaranteed Keys
Unlike groupingBy, which only creates map entries for keys that exist in the data, partitioningBy always includes both true and false keys, even if one list is empty. This eliminates null-check concerns.
Key Takeaway: partitioningBy is the specialized collector for binary classification, always returning a Map<Boolean, List<T>> with both true and false entries—use it when splitting data into exactly two categories based on a predicate.