Split data with partitioningBy
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A class report needs one list of students who passed and another of those who did not. Two filters over the same data feel repetitive.
One test, two groups
Collectors.partitioningBy splits elements into a Map with exactly two keys, true and false, based on a Predicate.
Many questions have a yes-or-no answer: did the student pass, is the fee paid, is the payment above the daily limit? The old way kept two lists and an if/else inside a loop.
Example 1 · Pass and fail: two lists in a loop versus partitioningBy
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.stream.Collectors;
public class PassFailDemo { public static void main(String[] args) { List<Integer> marks = List.of(72, 35, 91, 58, 28, 66);
// old way: two lists and an if/else List<Integer> passList = new ArrayList<>(); List<Integer> failList = new ArrayList<>(); for (int m : marks) { if (m >= 40) { passList.add(m); } else { failList.add(m); } } System.out.println("Loop: pass " + passList + ", fail " + failList);
// new way: one collector Map<Boolean, List<Integer>> result = marks.stream() .collect(Collectors.partitioningBy(m -> m >= 40)); System.out.println("Passed: " + result.get(true)); System.out.println("Failed: " + result.get(false)); System.out.println(result); }}Loop: pass [72, 91, 58, 66], fail [35, 28]
Passed: [72, 91, 58, 66]
Failed: [35, 28]
{false=[35, 28], true=[72, 91, 58, 66]}What this code does
- The predicate
m -> m >= 40puts every mark on one of two sides in a single pass.get(true)is the pass list andget(false)the fail list, each in the original order. - Printing the whole map shows
falsefirst andtruesecond. That order is fixed for the mappartitioningByreturns. - Why partitioningBy: it needs one pass and no
if/else, and both lists always exist, soget(false)is nevernulleven when nobody fails.
A stream version without collectors needed two passes: one filter for the yes side and one with the opposite test for the no side.
partitioningBy(predicate) does it in one pass. A predicate is a function that returns true or false, such as m -> m >= 40. The result is a Map<Boolean, List<T>>: get(true) holds the elements that passed the test, get(false) the rest, each list in stream order.
Both keys are always present
With groupingBy, a key exists only if some element produced it. If you group by m -> m >= 40 and every student passed, the false key is missing, get(false) returns null, and calling size() on it throws NullPointerException.
Example 2 · Both keys present, even when one side is empty
import java.util.List;import java.util.Map;import java.util.stream.Collectors;
public class EmptySideDemo { public static void main(String[] args) { List<Integer> marks = List.of(72, 81, 91, 58); // everyone passed
Map<Boolean, List<Integer>> grouped = marks.stream() .collect(Collectors.groupingBy(m -> m >= 40)); System.out.println("groupingBy keys: " + grouped.keySet()); System.out.println("groupingBy get(false): " + grouped.get(false)); try { System.out.println("Failed: " + grouped.get(false).size()); } catch (NullPointerException e) { System.out.println("groupingBy report crashed"); }
Map<Boolean, List<Integer>> parts = marks.stream() .collect(Collectors.partitioningBy(m -> m >= 40)); System.out.println("partitioningBy: " + parts); System.out.println("Failed: " + parts.get(false).size()); }}groupingBy keys: [true]
groupingBy get(false): null
groupingBy report crashed
partitioningBy: {false=[], true=[72, 81, 91, 58]}
Failed: 0What this code does
- Nobody failed, so
groupingBynever created afalsekey.get(false)returnsnull, and the report crashes onsize(). partitioningByalways creates both keys. Thefalseside is an empty list, so the same report line safely prints 0.
partitioningBy always creates both keys. If nobody failed, get(false) is an empty list, so size() is 0 and the report simply prints "Failed: 0". This is the main reason to prefer it for a yes-or-no split. The map it returns is a small special map that always prints false first, then true.
Predict the output
Predict the two buckets
Each program uses partitioningBy. What does it print?
Round 1 of 3
Every mark passes. What does this print?
Downstream collectors with partitioningBy
Like groupingBy, partitioningBy accepts a second collector that turns each side into a value: partitioningBy(m -> m >= 40, counting()) gives {false=2, true=6}, the fail and pass counts.
Example 3 · Downstream collectors: counts and averages for each side
import java.util.List;import java.util.Map;import java.util.stream.Collectors;
record Student(String name, int marks) {}
public class PassFailCountsDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Asha", 88), new Student("Ravi", 34), new Student("Neha", 93), new Student("Imran", 61), new Student("Kiran", 27), new Student("Divya", 75));
Map<Boolean, Long> counts = students.stream() .collect(Collectors.partitioningBy(s -> s.marks() >= 40, Collectors.counting())); Map<Boolean, Double> averages = students.stream() .collect(Collectors.partitioningBy(s -> s.marks() >= 40, Collectors.averagingInt(Student::marks))); Map<Boolean, List<String>> names = students.stream() .collect(Collectors.partitioningBy(s -> s.marks() >= 40, Collectors.mapping(Student::name, Collectors.toList())));
System.out.println("Passed: " + counts.get(true) + " " + names.get(true) + ", average " + averages.get(true)); System.out.println("Failed: " + counts.get(false) + " " + names.get(false) + ", average " + averages.get(false)); }}Passed: 4 [Asha, Neha, Imran, Divya], average 79.25 Failed: 2 [Ravi, Kiran], average 30.5
What this code does
counting(),averagingIntandmappingwork as downstream collectors exactly as they do withgroupingBy, but there are always just two keys.- The failed students' names come from
mapping(Student::name, toList()), ready for a remedial class list.
Example 4 · Real world: placement eligibility
import java.util.List;import java.util.Map;import java.util.function.Predicate;import java.util.stream.Collectors;
record Candidate(String name, double cgpa, int backlogs) {}
public class PlacementDemo { public static void main(String[] args) { List<Candidate> candidates = List.of( new Candidate("Asha", 8.4, 0), new Candidate("Ravi", 6.8, 0), new Candidate("Neha", 9.1, 1), new Candidate("Imran", 7.2, 0), new Candidate("Kiran", 7.9, 2), new Candidate("Divya", 7.0, 0));
Predicate<Candidate> eligible = c -> c.cgpa() >= 7.0 && c.backlogs() == 0;
Map<Boolean, List<String>> shortlist = candidates.stream() .collect(Collectors.partitioningBy(eligible, Collectors.mapping(Candidate::name, Collectors.toList())));
System.out.println("Eligible (" + shortlist.get(true).size() + "): " + shortlist.get(true)); System.out.println("Not eligible (" + shortlist.get(false).size() + "): " + shortlist.get(false)); }}Eligible (3): [Asha, Imran, Divya] Not eligible (3): [Ravi, Neha, Kiran]
What this code does
- The rule for a company drive is a yes-or-no test, so it is a
Predicate<Candidate>stored in a variable with a clear name. CGPA 7.0 counts as eligible because the test uses>=. - Neha has the highest CGPA but one backlog, so she lands on the
falseside. OnepartitioningBycall gives the placement cell both lists at once.
Every downstream from the Downstream collectors lesson works here: averagingInt for the average marks of each side, mapping(Student::name, toList()) for the names on each side, summingInt for the total amount on each side. An empty side gets the collector's empty value: 0 for counting, 0.0 for an average, an empty list for mapping.
partitioningBy versus groupingBy
Interviewers often ask when to use which. The short answer: a yes-or-no test means partitioningBy; anything with more than two categories means groupingBy.
Example 5 · Two groups or many: partitioningBy versus groupingBy
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Payment(String to, int amount) {}
public class SplitOrGroupDemo { static String size(int amount) { if (amount >= 10000) { return "large"; } else if (amount >= 1000) { return "medium"; } return "small"; }
public static void main(String[] args) { List<Payment> upi = List.of( new Payment("Rent", 12000), new Payment("Bookstore", 85), new Payment("Laptop EMI", 4500), new Payment("Metro", 40), new Payment("Fees", 25000));
// two sides: needs a second check or not Map<Boolean, Long> flagged = upi.stream() .collect(Collectors.partitioningBy(p -> p.amount() >= 10000, Collectors.counting())); System.out.println("Need a second check: " + flagged.get(true) + ", normal: " + flagged.get(false));
// three sizes: groupingBy Map<String, Long> bySize = upi.stream() .collect(Collectors.groupingBy(p -> size(p.amount()), Collectors.counting())); System.out.println("By size: " + new TreeMap<>(bySize)); }}Need a second check: 2, normal: 3
By size: {large=2, medium=1, small=2}What this code does
- "Is this payment above the limit?" has two answers, so
partitioningByfits and both counts are always there. - Small, medium and large are three categories, which a
Booleankey cannot hold, so the same data needsgroupingBywith a classifier that returns aString.
- Key type:
partitioningByalways hasBooleankeys;groupingByuses whatever the classifier returns. - Keys present:
partitioningByalways has both;groupingByhas only keys that occur. - Input:
partitioningBytakes aPredicate;groupingBytakes aFunction. - Use
groupingByfor grades A, B and C, branches or cities; usepartitioningByfor pass/fail or paid/unpaid.
Next step
Check your understanding
11 quick questions