Skip to lesson

Group data with groupingBy

Collectors.groupingBy splits a stream into groups. You give it a function that names the group of each element, and it returns a map from each group name to the list of elements in that group, such as branch → students of that branch.

Why grouping, and the old loop

Collectors.groupingBy puts elements into a Map whose keys come from a classifier function and whose values are the groups of matching elements.

Reports are full of groups: students by branch, orders by city, expenses by month. Before streams, every report wrote the same loop.

Example 1 · Students by branch: loop and groupingBy

ByBranchDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Student(String name, String branch, int year) {}
public class ByBranchDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE", 2),                new Student("Ravi", "ECE", 1),                new Student("Neha", "CSE", 1),                new Student("Imran", "MECH", 2),                new Student("Kiran", "ECE", 2),                new Student("Divya", "CSE", 2));
        // old way: look up the list, create it the first time, then add        Map<String, List<Student>> loopGroups = new HashMap<>();        for (Student s : students) {            List<Student> list = loopGroups.get(s.branch());            if (list == null) {                list = new ArrayList<>();                loopGroups.put(s.branch(), list);            }            list.add(s);        }
        // new way        Map<String, List<Student>> byBranch = students.stream()                .collect(Collectors.groupingBy(Student::branch));        System.out.println("Same groups: " + byBranch.equals(loopGroups));
        for (Map.Entry<String, List<Student>> e : new TreeMap<>(byBranch).entrySet()) {            List<String> names = new ArrayList<>();            for (Student s : e.getValue()) {                names.add(s.name());            }            System.out.println(e.getKey() + " -> " + names);        }    }}
Output
Same groups: true
CSE -> [Asha, Neha, Divya]
ECE -> [Ravi, Kiran]
MECH -> [Imran]

What this code does

  • groupingBy(Student::branch) builds the same Map<String, List<Student>> as the ten-line loop. The classifier Student::branch names the group of each student.
  • Inside each list the students keep input order: Asha before Neha before Divya. The program prints through new TreeMap<>(byBranch) so the branches come out A to Z instead of in HashMap order.
  • Why groupingBy: the loop needs a map, a check for a missing key and a new list for it. One groupingBy line replaces all of that and names the rule in a single place.

For each student, look up the branch in a map; if there is no list yet, create one and put it; then add the student to the list.

groupingBy(classifier) does that whole loop. The classifier is the function that gives the group key of one element, such as Student::branch. The result type is Map<K, List<T>>: for Stream<Student> grouped by a String branch, it is Map<String, List<Student>>.

How each element finds its group

groupingBy walks the stream once. For every element it calls the classifier to get the key, finds the list for that key (creating an empty list the first time the key appears), and adds the element to the end of that list.

groupingBy(Student::branch) reads five students in list order, Asha CSE, Neha ECE, Ravi CSE, Dev MECH and Kiran ECE, and builds a Map from branch to a list: CSE holds Asha and Ravi, ECE holds Neha and Kiran, MECH holds Dev.

Example 2 · The classifier can compute the key

GradeBandsDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
public class GradeBandsDemo {    static String grade(int marks) {        if (marks >= 80) {            return "A";        } else if (marks >= 60) {            return "B";        }        return "C";    }
    public static void main(String[] args) {        List<Integer> marks = List.of(91, 58, 73, 85, 64, 40, 77);
        Map<String, List<Integer>> bands = marks.stream()                .collect(Collectors.groupingBy(m -> grade(m)));        System.out.println(new TreeMap<>(bands));
        Map<Integer, List<String>> byLength = List.of("Goa", "Pune", "Agra", "Delhi", "Ooty").stream()                .collect(Collectors.groupingBy(String::length));        System.out.println(new TreeMap<>(byLength));    }}
Output
{A=[91, 85], B=[73, 64, 77], C=[58, 40]}
{3=[Goa], 4=[Pune, Agra, Ooty], 5=[Delhi]}

What this code does

  • The key does not have to be a field. Here the classifier calls grade(m), so marks are grouped into bands A, B and C. Each band lists its marks in input order.
  • Any type can be the key. Grouping words by String::length gives a Map<Integer, List<String>>. Only lengths that occur become keys, so there is no empty group for length 2.

Two facts follow from this. Inside each list, elements stay in stream order, so the first CSE student in the input is the first in the CSE list. And a key exists only if at least one element produced it: there are never empty groups.

Trace the code

Watch each student find a group

Step through and watch the map fill up.

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class GroupTrace {
public static void main(String[] args) {
List<String> students = List.of("Asha CSE", "Neha ECE", "Ravi CSE");
Map<String, List<String>> byBranch = students.stream()
.collect(Collectors.groupingBy(s -> {
String branch = s.substring(s.indexOf(' ') + 1);
System.out.println(s + " goes to " + branch);
return branch;
}));
System.out.println(byBranch);
}
}

Variables

None yet.

Output

(nothing printed yet)

Line 7Three students, each written as name and branch.

Step 1 of 8
If the classifier returns null for any element, groupingBy throws NullPointerException with the message "element cannot be mapped to a null key". Turn missing values into a real key, such as "UNKNOWN", inside the classifier.

Records as composite keys

Sometimes one field is not enough: you want students grouped by branch and year together. A composite key is a key made of several values.

Example 3 · A record as a composite key

CompositeKeyDemo.javaJava
import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Student(String name, String branch, int year) {}
record BranchYear(String branch, int year) {}
public class CompositeKeyDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE", 2),                new Student("Ravi", "ECE", 1),                new Student("Neha", "CSE", 1),                new Student("Imran", "CSE", 2),                new Student("Kiran", "ECE", 1));
        Map<BranchYear, List<Student>> groups = students.stream()                .collect(Collectors.groupingBy(s -> new BranchYear(s.branch(), s.year())));        System.out.println("Groups: " + groups.size());
        Map<BranchYear, List<Student>> sorted = new TreeMap<>(                Comparator.comparing(BranchYear::branch).thenComparingInt(BranchYear::year));        sorted.putAll(groups);        sorted.forEach((key, list) -> System.out.println(key.branch() + " year " + key.year()                + ": " + list.stream().map(Student::name).toList()));
        System.out.println("CSE 2nd years: "                + groups.get(new BranchYear("CSE", 2)).size());    }}
Output
Groups: 3
CSE year 1: [Neha]
CSE year 2: [Asha, Imran]
ECE year 1: [Ravi, Kiran]
CSE 2nd years: 2

What this code does

  • The classifier creates a new BranchYear for every student, yet students with the same branch and year land in one group. A record's generated equals and hashCode compare the field values, not the objects.
  • groups.get(new BranchYear("CSE", 2)) finds the group with a brand-new key object for the same reason. A TreeMap with a comparator on branch, then year, prints the groups in a fixed order.

Example 4 · Trap: a class key without equals and hashCode

BrokenKeyDemo.javaJava
import java.util.List;import java.util.Map;import java.util.stream.Collectors;
class SlotKey {    String day;    int period;
    SlotKey(String day, int period) {        this.day = day;        this.period = period;    }}
record SlotRecord(String day, int period) {}
public class BrokenKeyDemo {    public static void main(String[] args) {        List<String> bookings = List.of("Mon-1", "Mon-1", "Tue-2", "Mon-1");
        Map<SlotKey, List<String>> broken = bookings.stream()                .collect(Collectors.groupingBy(b -> new SlotKey(b.substring(0, 3),                        Integer.parseInt(b.substring(4)))));        System.out.println("Class key groups: " + broken.size());
        Map<SlotRecord, List<String>> fixed = bookings.stream()                .collect(Collectors.groupingBy(b -> new SlotRecord(b.substring(0, 3),                        Integer.parseInt(b.substring(4)))));        System.out.println("Record key groups: " + fixed.size());        System.out.println("Mon period 1 bookings: " + fixed.get(new SlotRecord("Mon", 1)).size());    }}
Output
Class key groups: 4
Record key groups: 2
Mon period 1 bookings: 3

What this code does

  • SlotKey uses the equals and hashCode it inherits from Object, which compare object identity. Every booking creates a new SlotKey, so all four bookings form four separate groups.
  • The same idea with a record gives 2 groups, and Monday period 1 correctly shows 3 bookings. If you must use a class, override equals and hashCode on its fields.

The old trick was to glue them into a string such as "CSE-2", which breaks as soon as a value contains a dash and must be split again later.

A record is the clean answer: record BranchYear(String branch, int year) {}. Java generates equals and hashCode from all its fields, so two BranchYear objects with the same branch and year are the same map key. The classifier becomes s -> new BranchYear(s.branch(), s.year()). A plain class without equals and hashCode does not work as a key: every new object is a different key, so every element lands in its own group.

The default map has no fixed order

Plain groupingBy(classifier) returns a HashMap today, and the documentation does not promise even that. A HashMap keeps no order: the branches may print as ECE, CSE, MECH on one run with one set of data and differently with another.

Java
Map<String, List<Student>> groups = students.stream()        .collect(Collectors.groupingBy(Student::branch));   // a HashMap: no fixed orderMap<String, List<Student>> sorted = new TreeMap<>(groups);  // keys from A to ZSystem.out.println(sorted.keySet());                        // [CSE, ECE, MECH]

Never build a report that depends on that order.

For a sorted printout, the simplest way is to copy the result into a TreeMap: new TreeMap<>(groups). For keys that are records, give the TreeMap a comparator. The Sorted and nested grouping lesson shows how to ask groupingBy for a TreeMap directly.

Example 5 · Trap: a null key, and the fix

NullKeyDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Student(String name, String branch) {}
public class NullKeyDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "CSE"),                new Student("Ravi", null),                new Student("Neha", "ECE"));
        try {            students.stream().collect(Collectors.groupingBy(Student::branch));        } catch (NullPointerException e) {            System.out.println("Error: " + e.getMessage());        }
        Map<String, List<Student>> safe = students.stream()                .collect(Collectors.groupingBy(                        s -> s.branch() == null ? "UNKNOWN" : s.branch()));        new TreeMap<>(safe).forEach((branch, list) ->                System.out.println(branch + ": " + list.size()));    }}
Output
Error: element cannot be mapped to a null key
CSE: 1
ECE: 1
UNKNOWN: 1

What this code does

  • Ravi has no branch, so the classifier returns null and groupingBy stops with NullPointerException. The message says exactly what went wrong.
  • The fix turns the missing value into a real key inside the classifier. Ravi now shows up in an UNKNOWN group that the office can follow up on, instead of crashing the report.

Example 6 · Real world: orders grouped by city for a dashboard

CityDashboardDemo.javaJava
import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Order(int id, String city, int amount) {}
public class CityDashboardDemo {    public static void main(String[] args) {        List<Order> orders = List.of(                new Order(501, "Pune", 1200),                new Order(502, "Delhi", 450),                new Order(503, "Pune", 300),                new Order(504, "Chennai", 2100),                new Order(505, "Delhi", 980),                new Order(506, "Pune", 640));
        Map<String, List<Order>> byCity = orders.stream()                .collect(Collectors.groupingBy(Order::city));
        System.out.println("City      Orders  Ids");        new TreeMap<>(byCity).forEach((city, list) -> System.out.printf("%-9s %6d  %s%n",                city, list.size(), list.stream().map(Order::id).toList()));
        String busiest = "";        int most = 0;        for (Map.Entry<String, List<Order>> e : byCity.entrySet()) {            if (e.getValue().size() > most) {                most = e.getValue().size();                busiest = e.getKey();            }        }        System.out.println("Busiest city: " + busiest + " (" + most + " orders)");    }}
Output
City      Orders  Ids
Chennai        1  [504]
Delhi          2  [502, 505]
Pune           3  [501, 503, 506]
Busiest city: Pune (3 orders)

What this code does

  • One groupingBy(Order::city) call gives the dashboard everything it needs: each city's list of orders, from which it shows the count and the ids.
  • The table is printed through a TreeMap, so cities appear A to Z. Finding the busiest city looks at sizes only, so the HashMap order does not change the answer. The Downstream collectors lesson replaces list.size() with a counting() collector.

Next step

Check your understanding

11 quick questions