Java
partitioningBy
Learn two-way partitioning with Collectors.partitioningBy.
Splitting in two: partitioningBy
Collectors.partitioningBy splits elements into two groups based on a single condition. The condition is a Predicate<T> and the result is always Map<Boolean, List<T>>: the true key holds elements that match, the false key those that do not.
Example: numbers.stream().collect(Collectors.partitioningBy(n -> n % 2 == 0)). Even numbers land in the true group, odd ones in false. Unlike groupingBy, this collector always produces exactly two groups.
partitioningBy with a downstream collector
The two-argument overload applies a downstream collector to each partition. This is handy not only for keeping lists but for counting or averaging each side.
Example: Collectors.partitioningBy(n -> n % 2 == 0, Collectors.counting()). This call returns Map<Boolean, Long>: true is the number of even values, false the number of odd ones. You get a summary of each partition in a single line, with no extra pass needed.
Exercise Partition numbers by even/odd
Create a list of the numbers 1, 2, 3, 4, 5. Partition the stream with Collectors.partitioningBy(n -> n % 2 == 0). Then print the counts of the false and true keys on separate lines using System.out.println; print false: first, then true: .
Show example solution
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class PartitionNumbers {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
Map<Boolean, List<Integer>> parts = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println("false: " + parts.get(false).size());
System.out.println("true: " + parts.get(true).size());
}
}
Test yourself
-
Match the partitioningBy concepts
- partitioningBy
- Splits in two
- Predicate<T>
- Condition function
- true key
- Matching elements
- false key
- Non-matching elements
-
What type does partitioningBy(n -> n % 2 == 0) return?
- List<Integer>
- Map<Boolean, Long>
- Map<Boolean, List<Integer>>
- Optional<Integer>
Show answer
Map<Boolean, List<Integer>> — The single-argument partitioningBy returns Map<Boolean, List<T>>.
-
Complete the partitioningBy call
Map<Boolean, List<Integer>> parts = numbers.stream()
.collect(Collectors.partitioningBy(____));
Show answer
Map<Boolean, List<Integer>> parts = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
Next lesson: joining