Collectors.partitioningBy method¶
Collectors.partitioningBy is a static method in the java.util.stream.Collectors class used to process a stream of elements and divide them into two groups based on a Predicate.^[600-developer-java-java8-java8-collect.md]
Method Signatures¶
There are two overloaded versions of the partitioningBy method:
- partitioningBy(Predicate): Partitions the input elements based on the provided predicate.^[600-developer-java-java8-java8-collect.md]
- partitioningBy(Predicate, Collector): Partitions the input elements based on the provided predicate and applies a downstream collector to the values in each partition.^[600-developer-java-java8-java8-collect.md]
Usage¶
The primary use case for this collector is to categorize stream elements by a boolean condition.^[600-developer-java-java8-java8-collect.md]
Basic Partitioning¶
The first variant accepts a Predicate lambda expression.^[600-developer-java-java8-java8-collect.md] For example, to split a list of students into those with high scores and others:
collect(Collectors.partitioningBy(student -> student.getScore() >= 90));
Partitioning with a Downstream Collector¶
The second variant allows an additional Collector to be passed, which is applied to the values in each partition to perform a reduction or other operation.^[600-developer-java-java8-java8-collect.md] For instance, to count the number of elements in each group:
collect(Collectors.partitioningBy(student -> student.getScore() >= 90, Collectors.counting()));
Related Concepts¶
- [[Stream API]]
- [[Collectors.groupingBy]]
Sources¶
^[600-developer-java-java8-java8-collect.md]