Sorted and nested grouping
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)groupingBy can build any kind of map you ask for: pass TreeMap::new and the groups come out sorted by key. Put a second groupingBy inside the first, and you get a map of maps, such as city → category → total sales.
TreeMap::new as the map supplier
So far, sorted reports copied the result into a TreeMap before printing. That works, but it builds the map twice and the type in your code still says plain Map. The three-argument form asks for the right map from the start: groupingBy(classifier, mapFactory, downstream).
Example 1 · TreeMap::new: sorted keys from the start
import java.util.Comparator;import java.util.List;import java.util.TreeMap;import java.util.stream.Collectors;
record Student(String name, String branch, int year) {}
public class SortedGroupsDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Asha", "MECH", 2), new Student("Ravi", "CSE", 1), new Student("Neha", "ECE", 3), new Student("Imran", "CSE", 2), new Student("Kiran", "MECH", 1));
TreeMap<String, List<Student>> byBranch = students.stream() .collect(Collectors.groupingBy(Student::branch, TreeMap::new, Collectors.toList())); System.out.println("Branches: " + byBranch.keySet()); System.out.println("First branch: " + byBranch.firstKey());
TreeMap<Integer, Long> perYear = students.stream() .collect(Collectors.groupingBy(Student::year, TreeMap::new, Collectors.counting())); System.out.println("Per year: " + perYear);
TreeMap<String, Long> zToA = students.stream() .collect(Collectors.groupingBy(Student::branch, () -> new TreeMap<String, Long>(Comparator.reverseOrder()), Collectors.counting())); System.out.println("Z to A: " + zToA); }}Branches: [CSE, ECE, MECH]
First branch: CSE
Per year: {1=2, 2=2, 3=1}
Z to A: {MECH=2, ECE=1, CSE=2}What this code does
- The middle argument
TreeMap::newmakesgroupingBybuild aTreeMap, so the branches are sorted without a copy, and the variable can be typedTreeMapto usefirstKey(). The downstreamtoList()must be written in this form. - Year numbers sort from 1 upward. For Z to A, the supplier is a lambda that passes
Comparator.reverseOrder(), with the types written asTreeMap<String, Long>so the line compiles.
The map factory is a supplier that creates the empty map, usually TreeMap::new. The keys are then kept sorted by their natural order: A to Z for strings, small to large for numbers. The downstream comes last and is required, so write toList() when you just want the lists. For another key order, pass a lambda that builds the TreeMap with a comparator, and name its types: () -> new TreeMap<String, Long>(Comparator.reverseOrder()). With the empty <>, Java cannot work out the types and the line does not compile.
LinkedHashMap keeps a chosen order
Some orders are not sorted orders: Monday to Friday, the order of a price list, or the order of rounds in a contest. Alphabetical order would put Friday first.
Example 2 · LinkedHashMap: timetable days in calendar order
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Period(String day, String subject) {}
public class TimetableDemo { public static void main(String[] args) { List<Period> timetable = List.of( new Period("Mon", "Maths"), new Period("Mon", "Physics"), new Period("Tue", "Chemistry"), new Period("Wed", "Maths"), new Period("Wed", "English"), new Period("Fri", "Lab"));
Map<String, List<String>> sortedByName = timetable.stream() .collect(Collectors.groupingBy(Period::day, TreeMap::new, Collectors.mapping(Period::subject, Collectors.toList()))); System.out.println("TreeMap: " + sortedByName.keySet());
Map<String, List<String>> calendar = timetable.stream() .collect(Collectors.groupingBy(Period::day, LinkedHashMap::new, Collectors.mapping(Period::subject, Collectors.toList()))); System.out.println("LinkedHashMap: " + calendar.keySet()); calendar.forEach((day, subjects) -> System.out.println(day + " " + subjects)); }}TreeMap: [Fri, Mon, Tue, Wed] LinkedHashMap: [Mon, Tue, Wed, Fri] Mon [Maths, Physics] Tue [Chemistry] Wed [Maths, English] Fri [Lab]
What this code does
- A
TreeMapsorts the day names as text, so Fri comes first, which is wrong for a timetable. LinkedHashMap::newkeeps the days in the order they first appear in the input, which is already Monday to Friday. The input order becomes the report order.
LinkedHashMap::new as the map factory keeps keys in the order they first appeared in the stream. So you control the order through the input: if the timetable lists Monday first, Monday is the first key. If the input is not in the order you want, sorted(...) the stream before grouping.
Sorting by value with Map.Entry.comparingByValue
A TreeMap sorts by key. A "top categories by revenue" report must sort by value. A map cannot do that by itself, so stream its entries: map.entrySet().stream(). Each element is a Map.Entry, a key-value pair with getKey() and getValue().
Example 3 · Top categories by revenue: sorting entries by value
import java.util.Comparator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.stream.Collectors;
record Sale(String category, int amount) {}
public class TopCategoriesDemo { public static void main(String[] args) { List<Sale> sales = List.of( new Sale("Books", 450), new Sale("Mobiles", 15999), new Sale("Toys", 900), new Sale("Books", 1200), new Sale("Stationery", 300), new Sale("Toys", 400), new Sale("Shoes", 1100), new Sale("Stationery", 120));
Map<String, Integer> revenue = sales.stream() .collect(Collectors.groupingBy(Sale::category, Collectors.summingInt(Sale::amount)));
Map<String, Integer> top3 = revenue.entrySet().stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .limit(3) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new)); System.out.println("Top 3: " + top3);
// class rep votes: Asha and Neha tie, so break the tie by name Map<String, Integer> votes = Map.of("Asha", 12, "Ravi", 15, "Neha", 12, "Kiran", 7); votes.entrySet().stream() .sorted(Map.Entry.<String, Integer>comparingByValue().reversed() .thenComparing(Map.Entry.comparingByKey())) .forEach(e -> System.out.println(e.getKey() + " " + e.getValue())); }}Top 3: {Mobiles=15999, Books=1650, Toys=1300}
Ravi 15
Asha 12
Neha 12
Kiran 7What this code does
entrySet().stream()turns the map into a stream of key-value pairs.comparingByValue(Comparator.reverseOrder())sorts them by revenue, highest first, andlimit(3)keeps the top three. Collecting into aLinkedHashMapkeeps that order.- In the votes, Asha and Neha tie on 12.
Map.ofgives no fixed iteration order, so without a tie-breaker the two could swap between runs.thenComparing(Map.Entry.comparingByKey())puts tied names in A to Z order. The type witness<String, Integer>lets.reversed()compile.
Example 4 · Trap: comparingByValue().reversed() loses the types
import java.util.List;import java.util.Map;import java.util.stream.Collectors;
record Sale(String category, int amount) {}
public class TopCategoriesDemo { public static void main(String[] args) { List<Sale> sales = List.of(new Sale("Books", 450), new Sale("Toys", 900)); Map<String, Integer> revenue = sales.stream() .collect(Collectors.groupingBy(Sale::category, Collectors.summingInt(Sale::amount)));
revenue.entrySet().stream() .sorted(Map.Entry.comparingByValue().reversed()) .forEach(e -> System.out.println(e.getKey() + " " + e.getValue())); }}TopCategoriesDemo.java:14: error: incompatible types: Comparator<Entry<Object,V>> cannot be converted to Comparator<? super Entry<String,Integer>>
.sorted(Map.Entry.comparingByValue().reversed())
^
where V is a type-variable:
V extends Comparable<? super V>
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorWhat this code does
comparingByValue()is followed by.reversed(), so Java types it on its own, without looking atsorted. It cannot learn the key type and falls back toObject, which no longer fitsEntry<String, Integer>.- Two fixes:
Map.Entry.comparingByValue(Comparator.reverseOrder()), or name the types withMap.Entry.<String, Integer>comparingByValue().reversed(). It is the same trap asComparator.comparing(...).reversed().
Map.Entry.comparingByValue() compares entries by value, smallest first. For largest first, write Map.Entry.comparingByValue(Comparator.reverseOrder()). Add limit(3) for a top three, and collect into a LinkedHashMap with toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new) so the sorted order survives. The trap: Map.Entry.comparingByValue().reversed() does not compile. As with Comparator.comparing(...).reversed(), the chain hides the types, so Java uses Object. Pass Comparator.reverseOrder() inside instead, or write the types: Map.Entry.<String, Integer>comparingByValue().reversed().
Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()) puts equal values in key order.Two-level grouping: a map of maps
A sales head asks: for each city, the total for each category. The downstream of the first groupingBy can be another groupingBy: groupingBy(Order::city, TreeMap::new, groupingBy(Order::category, TreeMap::new, summingInt(Order::amount))).
Example 5 · Two-level grouping: city, then category
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Order(String city, String category, int amount) {}
public class CityCategoryDemo { public static void main(String[] args) { List<Order> orders = List.of( new Order("Pune", "Books", 450), new Order("Delhi", "Mobiles", 15999), new Order("Pune", "Mobiles", 8999), new Order("Pune", "Books", 300), new Order("Delhi", "Books", 650), new Order("Chennai", "Toys", 900), new Order("Delhi", "Mobiles", 12499));
Map<String, Map<String, Integer>> report = orders.stream() .collect(Collectors.groupingBy(Order::city, TreeMap::new, Collectors.groupingBy(Order::category, TreeMap::new, Collectors.summingInt(Order::amount))));
System.out.println(report); report.forEach((city, byCategory) -> { System.out.println(city); byCategory.forEach((category, total) -> System.out.println(" " + category + ": Rs " + total)); }); System.out.println("Pune books: Rs " + report.get("Pune").get("Books")); }}{Chennai={Toys=900}, Delhi={Books=650, Mobiles=28498}, Pune={Books=750, Mobiles=8999}}
Chennai
Toys: Rs 900
Delhi
Books: Rs 650
Mobiles: Rs 28498
Pune
Books: Rs 750
Mobiles: Rs 8999
Pune books: Rs 750What this code does
- The outer
groupingBysplits orders by city; its downstream is a secondgroupingBythat splits each city's orders by category and adds the amounts. The type isMap<String, Map<String, Integer>>. - Both levels use
TreeMap::new, so cities and the categories inside each city are sorted. Twogetcalls read one cell of the report, like a row and a column in a table.
Example 6 · Real world: a sorted month-wise sales report
import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Sale(int month, String category, int amount) {}
public class MonthlyReportDemo { static final String[] MONTHS = {"", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
public static void main(String[] args) { List<Sale> sales = List.of( new Sale(3, "Books", 1200), new Sale(1, "Mobiles", 15999), new Sale(3, "Toys", 900), new Sale(1, "Books", 450), new Sale(2, "Books", 700), new Sale(3, "Books", 650), new Sale(2, "Mobiles", 8999), new Sale(1, "Toys", 300));
TreeMap<Integer, Map<String, Integer>> byMonth = sales.stream() .collect(Collectors.groupingBy(Sale::month, TreeMap::new, Collectors.groupingBy(Sale::category, TreeMap::new, Collectors.summingInt(Sale::amount))));
System.out.printf("%-5s %8s %s%n", "Month", "Total", "Best category"); byMonth.forEach((month, cats) -> { int total = cats.values().stream().mapToInt(Integer::intValue).sum(); String best = cats.entrySet().stream() .max(Map.Entry.<String, Integer>comparingByValue() .thenComparing(Map.Entry.comparingByKey(Comparator.reverseOrder()))) .get().getKey(); System.out.printf("%-5s %8d %s%n", MONTHS[month], total, best); }); }}Month Total Best category Jan 16749 Mobiles Feb 9699 Mobiles Mar 2750 Books
What this code does
- Month numbers as keys in a
TreeMapgive January, February, March in calendar order, whatever order the sales arrive in. A month name as text would sort Feb before Jan. - Inside each month,
maxwithcomparingByValuefinds the best category. The tie-breaker prefers the name earlier in the alphabet, so the report is the same on every run.
The result type is Map<String, Map<String, Integer>>: the outer key is the city, the inner key is the category. Read it with two lookups, report.get("Pune").get("Books"), or print it with two nested forEach calls. Give both levels a TreeMap::new so the whole report is sorted. Keep nesting to two levels. Three or more levels are hard to read; at that point a record key such as record CityCategory(String city, String category) is often clearer.
Next step
Check your understanding
11 quick questions