Video in progress
What is the difference between partitioningBy and groupingBy, and when is each convenient?
partitioningBy splits into two groups by a predicate and returns a Map<Boolean, ...> whose keys are only true/false, and both keys are always present. groupingBy creates many groups by any key.
📖 Answer
Map<Boolean, List<Student>> passed = students.stream()
.collect(Collectors.partitioningBy(s -> s.score() >= 60));
List<Student> ok = passed.get(true);
List<Student> failed = passed.get(false);
The main practical difference: even if nobody failed, passed.get(false) returns an empty list, not null. With groupingBy(s -> s.score() >= 60), there is no such key at all and get(false) gives null, which is a short road to an NPE.
You can pass a downstream collector too:
Map<Boolean, Long> counts = students.stream()
.collect(Collectors.partitioningBy(s -> s.score() >= 60, Collectors.counting()));
When to use which: if the condition is yes/no, partitioningBy. If the key takes three or more values (status, city, category), groupingBy.
Sign up to mark studied questions and save your progress.