partitioningBy and counting
Split a stream into two groups with partitioningBy and count elements with counting.
partitioningBy Basics
Collectors.partitioningBy(predicate) splits a stream into exactly two groups — true and false — and returns a Map<Boolean, List<T>>.
import java.util.*;
import java.util.stream.*;
List<Integer> nums = List.of(1,2,3,4,5,6,7,8,9,10);
Map<Boolean, List<Integer>> evenOdd =
nums.stream().collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println(evenOdd.get(true)); // [2, 4, 6, 8, 10]
System.out.println(evenOdd.get(false)); // [1, 3, 5, 7, 9]partitioningBy vs filter
Unlike filter, partitioningBy retains both groups simultaneously — useful when you need both halves of the partition.
record Student(String name, int score) {}
List<Student> students = List.of(
new Student("Alice",90), new Student("Bob",55),
new Student("Carol",72), new Student("Dave",48)
);
Map<Boolean, List<Student>> result =
students.stream().collect(
Collectors.partitioningBy(s -> s.score() >= 60)
);
System.out.println("Passed: " + result.get(true).size());
System.out.println("Failed: " + result.get(false).size());All lessons in this course
- groupingBy: Classifying Elements
- partitioningBy and counting
- toMap, joining, and summarizing
- Building a Custom Collector