Collectors.partitioningBy()
Splits stream elements into two groups by a condition.
Available since: Java 8
Syntax
static <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate)Parameters
| Parameter | Type | Description |
|---|---|---|
| predicate | Predicate<? super T> | The partitioning condition. |
Return value
Collector<T, ?, Map<Boolean, List<T>>>A collector into a map with the keys `false` and `true`.
Examples
Passed and failed:
void main() {
Map<Boolean, List<Integer>> parts = Stream.of(45, 82, 67, 30, 91)
.collect(Collectors.partitioningBy(score -> score >= 60));
IO.println("passed: " + parts.get(true));
IO.println("failed: " + parts.get(false));
}Output:
passed: [82, 67, 91]
failed: [45, 30]Notes
The result always has both keys, even if one group is empty. A collector can be passed as the second argument, for example Collectors.counting(). For more than two groups use groupingBy().
See also
- Collectors.groupingBy() — A collector that sorts elements into groups that share a key.
- Stream.filter() — Keeps only the stream elements that match a condition.
Related recipes
In the tutorial
- Grouping — Grouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.