Collectors: practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most collector bugs come from four habits: assuming keys are unique, trusting the order of a HashMap, picking a collector that drops empty groups, and letting null reach a map. Each one has a short, reliable fix.
Mistake 1: assuming keys are unique
Two-argument toMap works in testing with clean data, then throws IllegalStateException: Duplicate key on the first real file where a name, a city or a date repeats.
Example 1 · Mistake: duplicate key in a UPI contact map
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Txn(String upiId, String name, int amount) {}
public class DuplicateKeyFixDemo { public static void main(String[] args) { List<Txn> txns = List.of( new Txn("ravi@upi", "Ravi", 200), new Txn("bookstore@upi", "Bookstore", 60), new Txn("ravi@upi", "Ravi K", 150), new Txn("metro@upi", "Metro", 40));
try { Map<String, String> names = txns.stream() .collect(Collectors.toMap(Txn::upiId, Txn::name)); System.out.println(names); } catch (IllegalStateException e) { System.out.println("Broken: " + e.getMessage()); }
Map<String, String> latestName = txns.stream() .collect(Collectors.toMap(Txn::upiId, Txn::name, (oldV, newV) -> newV, TreeMap::new)); System.out.println("Latest name: " + latestName);
Map<String, Integer> totalPaid = txns.stream() .collect(Collectors.toMap(Txn::upiId, Txn::amount, Integer::sum, TreeMap::new)); System.out.println("Total paid: " + totalPaid); }}Broken: Duplicate key ravi@upi (attempted merging values Ravi and Ravi K)
Latest name: {bookstore@upi=Bookstore, metro@upi=Metro, ravi@upi=Ravi K}
Total paid: {bookstore@upi=60, metro@upi=40, ravi@upi=350}What this code does
- Ravi was paid twice, so his UPI id is a repeated key and two-argument
toMapthrows. The message names the key and both values. - The fix depends on the question. For the saved contact name, keep the latest value with
(oldV, newV) -> newV. For money paid, add the amounts withInteger::sum.TreeMap::newmakes both outputs sorted.
Before writing toMap, ask whether two elements can ever give the same key. If yes, decide what should happen and say it with a merge function: keep the first (a, b) -> a, keep the last (a, b) -> b, add Integer::sum, or keep the larger Math::max. If many values per key is the normal case, you probably want groupingBy, not toMap.
Mistake 2: trusting HashMap order
toSet, toMap and groupingBy give hash-based results by default. Their printed order can look sorted for small numbers, then change when the data or the Java version changes. A report or a test that depends on it is a bug waiting to happen.
Example 2 · Mistake: unordered output, and three fixes
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
public class OrderFixDemo { public static void main(String[] args) { List<String> visits = List.of("Pune", "Agra", "Pune", "Goa", "Kochi", "Agra", "Pune");
// fix 1: sorted keys Map<String, Long> sorted = visits.stream() .collect(Collectors.groupingBy(c -> c, TreeMap::new, Collectors.counting())); System.out.println("By name: " + sorted);
// fix 2: first-seen order Map<String, Long> firstSeen = visits.stream() .collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting())); System.out.println("By first trip: " + firstSeen);
// fix 3: by count, highest first, ties by name String byCount = sorted.entrySet().stream() .sorted(Map.Entry.<String, Long>comparingByValue().reversed() .thenComparing(Map.Entry.comparingByKey())) .map(e -> e.getKey() + "=" + e.getValue()) .collect(Collectors.joining(", ")); System.out.println("By count: " + byCount); }}By name: {Agra=2, Goa=1, Kochi=1, Pune=3}
By first trip: {Pune=3, Agra=2, Goa=1, Kochi=1}
By count: Pune=3, Agra=2, Goa=1, Kochi=1What this code does
- The same counts can be shown in three orders, and each needs a different tool:
TreeMap::newfor names,LinkedHashMap::newfor the order of first visits, and sorted entries for counts. - Goa and Kochi tie on 1 visit. The
comparingByKey()tie-breaker puts Goa first every time, so the output never depends on hash order.
Ask for the order you need. Sorted keys: TreeMap::new as the map supplier. First-seen order: LinkedHashMap::new. Sorted by value: stream the entries, sort them with Map.Entry.comparingByValue(...), and add comparingByKey() as a tie-breaker so equal values always come out the same way.
Mistake 3: a collector that drops empty groups
groupingBy creates only the keys it sees. Grouping by m -> m >= 40 when everyone passed leaves no false key, and get(false).size() crashes. filter before groupingBy removes a branch completely when none of its students qualify.
Example 3 · A branch-wise result report: counts and averages
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Result(String name, String branch, int marks) {}
public class BranchReportDemo { public static void main(String[] args) { List<Result> results = List.of( new Result("Asha", "CSE", 88), new Result("Ravi", "ECE", 34), new Result("Neha", "CSE", 91), new Result("Imran", "MECH", 61), new Result("Kiran", "ECE", 79), new Result("Divya", "CSE", 38), new Result("Arjun", "MECH", 72), new Result("Zoya", "ECE", 55));
Map<String, Long> total = results.stream() .collect(Collectors.groupingBy(Result::branch, TreeMap::new, Collectors.counting())); Map<String, Long> passed = results.stream() .collect(Collectors.groupingBy(Result::branch, Collectors.filtering(r -> r.marks() >= 40, Collectors.counting()))); Map<String, Double> average = results.stream() .collect(Collectors.groupingBy(Result::branch, Collectors.averagingInt(Result::marks))); Map<Boolean, Long> overall = results.stream() .collect(Collectors.partitioningBy(r -> r.marks() >= 40, Collectors.counting()));
System.out.println("Branch Students Passed Average"); total.forEach((b, n) -> System.out.printf("%-6s %8d %6d %7.1f%n", b, n, passed.get(b), average.get(b))); System.out.println("Overall: " + overall.get(true) + " passed, " + overall.get(false) + " failed"); }}Branch Students Passed Average CSE 3 2 72.3 ECE 3 2 56.0 MECH 2 2 66.5 Overall: 6 passed, 2 failed
What this code does
- Each column is one collector:
counting()for students,filtering(..., counting())for passes (so a branch with no passes would still show 0), andaveragingIntfor the average. TheTreeMapfrom the first map fixes the row order. - The overall line uses
partitioningBy, which always has both the pass and fail counts, even on a day when nobody fails.
For a yes-or-no split, use partitioningBy: both keys are always there. To count only some elements per group while keeping every group, use filtering as the downstream collector. Also remember the types: counting() gives Long, averagingInt gives Double.
Mistake 4: null keys and values
Real data has blanks. groupingBy throws NullPointerException ("element cannot be mapped to a null key") when the classifier returns null, and toMap throws it when a value is null. toUnmodifiableSet and toUnmodifiableList reject null elements too.
List<Friend> friends = List.of(new Friend("Asha", "Pune"), new Friend("Ravi", null));// groupingBy(Friend::city) throws NullPointerException: element cannot be mapped to a null keyMap<String, Long> perCity = friends.stream() .collect(Collectors.groupingBy(f -> f.city() == null ? "UNKNOWN" : f.city(), Collectors.counting()));long withCity = friends.stream().map(Friend::city).filter(Objects::nonNull).count();Decide what a blank means before collecting. Either drop it with filter(Objects::nonNull) or a field check, or turn it into a real value such as "UNKNOWN" or "not given" inside the key or value function.
Choosing the right collector
Read the question the report asks, then pick the collector that answers it directly.
Example 4 · Word frequency sorted by count
import java.util.Arrays;import java.util.Map;import java.util.stream.Collectors;
public class WordFrequencyDemo { public static void main(String[] args) { String feedback = "Good lab. Good faculty, but the lab is crowded. " + "The faculty is good and the library is good";
Map<String, Long> freq = Arrays.stream(feedback.toLowerCase().split("[^a-z]+")) .filter(w -> !w.isEmpty()) .collect(Collectors.groupingBy(w -> w, Collectors.counting()));
freq.entrySet().stream() .sorted(Map.Entry.<String, Long>comparingByValue().reversed() .thenComparing(Map.Entry.comparingByKey())) .limit(5) .forEach(e -> System.out.println(e.getKey() + " " + e.getValue())); }}good 4 is 3 the 3 faculty 2 lab 2
What this code does
- The text is made lowercase so
Goodandgoodcount as one word, then split on anything that is not a letter.groupingBy(w -> w, counting())counts each word. - The entries are sorted by count, highest first, with ties in A to Z order, and
limit(5)keeps the top five. This is the classic word frequency task: group, count, sort entries by value.
- One value per unique key (id → student):
toMap, with a merge function if keys can repeat. - Many values per key (branch → students):
groupingBy, plus a downstream for counts, sums, averages or names. - Exactly two sides from a test (pass/fail):
partitioningBy. - Several statistics at once:
summarizingInt; two different results combined:teeing; one line of text:joining.
Finish up
Mark complete & continue
Next: IntStream, LongStream and DoubleStream