Partitioning groups data into two groups: for one group a condition is true; for the other, the same condition is false.
The partitioning condition is specified using a Predicate.
Collectors class method partitioningBy() is overloaded and it has two versions:
partitioningBy(Predicate<? super T> predicate) partitioningBy(Predicate<? super T> predicate, Collector<? super T,A,D> downstream)
partitionedBy() method returns a collector that performs the partitioning based on the specified predicate.
The values for a key are stored in a List.
If the predicate evaluates to true, the element is added to the list for the key with true value.
The following code partitions people based on whether the person is a male or not:
Map<Boolean, List<Person>> partionedByMaleGender = Person.persons() .stream() .collect(Collectors.partitioningBy(Person::isMale));
You can specify another collector that can perform a reduction operation on the values for each key.
The following code partitions people into male and non-male, and collects their names in a comma-separated string:
Map<Boolean,String> partionedByMaleGender =
Person.persons()
.stream()
.collect(Collectors.partitioningBy(Person::isMale,
Collectors.mapping(Person::getName, Collectors.joining(", "))));