partitioningBy collector¶
In the context of the Java Stream API, the partitioningBy collector is a static method provided by the java.util.stream.Collectors class^[600-developer__java__java8__java8-collect.md]. It is used to divide a stream of elements into two groups based on a boolean condition (a Predicate)^[600-developer__java__java8__java8-collect.md].
Method Signatures¶
The partitioningBy collector generally provides two overloaded methods^[600-developer__java__java8__java8-collect.md]:
- partitioningBy(Predicate): Accepts a single predicate to categorize elements.
- partitioningBy(Predicate, Collector): Accepts a predicate and a downstream collector to perform a further reduction operation on the values within each partition.
Usage Examples¶
- Basic Partitioning: You can separate elements into a
Map<Boolean, List>based on a condition. For example, to split a list of students based on a score threshold:java collect(Collectors.partitioningBy(student -> student.getScore() >= 90));^[600-developer__java__java8__java8-collect.md] - Partitioning with Aggregation: You can perform an aggregation, such as counting, within the partitions. For example, to count the number of elements in each group:
java collect(Collectors.partitioningBy(student -> student.getScore() >= 90, Collectors.counting()));^[600-developer__java__java8__java8-collect.md]
Related Concepts¶
Sources¶
600-developer__java__java8__java8-collect.md