Code Snippets
/

Group by Key with Stream Collectors

Group by Key with Stream Collectors

`Collectors.groupingBy` is the Java equivalent of SQL `GROUP BY`: pass a key extractor and you get back a `Map<K, List<T>>`. This snippet covers the basic grouping, downstream collectors (counting, summing, mapping to a different value), and multi-level grouping by chaining two `groupingBy` calls. Pair with `LinkedHashMap` when you need stable insertion order.

Java
Medium
3 snippets
java-streams
java-collections
implementation

311 views

7

import java.util.*;
import java.util.stream.*;

public class Main {
    static final class Order {
        final String customer; final String product; final int qty;
        Order(String c, String p, int q) { customer = c; product = p; qty = q; }
        public String customer() { return customer; }
        public String product()  { return product; }
        public int qty()         { return qty; }
        public String toString() { return customer + "/" + product + "x" + qty; }
    }

    public static void main(String[] args) {
        List<Order> orders = Arrays.asList(
                new Order("ada",   "book",   2),
                new Order("ada",   "pen",    5),
                new Order("linus", "book",   1),
                new Order("linus", "laptop", 1)
        );
        Map<String, List<Order>> byCustomer = orders.stream()
                .collect(Collectors.groupingBy(Order::customer));
        byCustomer.forEach((k, v) -> System.out.println(k + " -> " + v));
    }
}

Collectors.groupingBy(keyExtractor) walks the stream once and bins each element under the key returned by the extractor. The default downstream collector is toList, so the value type is List<T>. The result is a HashMap, which means key iteration order is not stable: pass groupingBy(key, LinkedHashMap::new, toList()) if you need insertion order. On JDK 16+ the Order class collapses to record Order(String customer, String product, int qty) {}.