Basic partitioningBy Syntax and Usage
You'll learn how to split a stream into exactly two groups using a simple predicate.
The Core Idea
While groupingBy creates a Map with many possible keys, partitioningBy always produces exactly two groups: those matching a predicate (true) and those that don't (false). The result is always a Map<Boolean, List<T>> with two entries.
Think of it like sorting laundry: groupingBy creates piles by color (red, blue, green...), but partitioningBy creates just two piles—lights and darks.
The Syntax
Collectors.partitioningBy(Predicate<T> predicate)
The predicate determines which group each element falls into.
Concrete Examples
Example 1: Separating Even and Odd Numbers
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println(partitioned.get(true)); // [2, 4, 6, 8, 10]
System.out.println(partitioned.get(false)); // [1, 3, 5, 7, 9]
Example 2: Passing and Failing Students
List<Integer> scores = List.of(85, 42, 91, 58, 73, 39, 88);
Map<Boolean, List<Integer>> results = scores.stream()
.collect(Collectors.partitioningBy(score -> score >= 60));
System.out.println("Passing: " + results.get(true)); // [85, 91, 73, 88]
System.out.println("Failing: " + results.get(false)); // [42, 58, 39]
Both keys (true and false) always exist in the result map, even if one group is empty.
Key Takeaway: Use partitioningBy(predicate) when you need to split a stream into exactly two groups based on a true/false condition—the result is always a Map<Boolean, List<T>> with both keys present.