Java

Collectors.groupingBy — Group by Key

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Like SQL GROUP BY for streams. Produces a `Map<K, List<V>>` (or any downstream collector you specify). Indispensable for analytics-style aggregations.
Java
Raw
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;

class Demo {
    record Sale(String region, String product, double amount) {}

    void example() {
        var sales = List.of(
            new Sale("US", "Widget", 100),
            new Sale("US", "Gizmo",  150),
            new Sale("EU", "Widget", 200),
            new Sale("EU", "Widget", 80),
            new Sale("US", "Widget", 90)
        );

        // Group by region → Map<String, List<Sale>>
        Map<String, List<Sale>> byRegion = sales.stream()
            .collect(groupingBy(Sale::region));

        // Group by region, downstream → sum the amounts
        Map<String, Double> revenueByRegion = sales.stream()
            .collect(groupingBy(Sale::region, summingDouble(Sale::amount)));
        System.out.println(revenueByRegion);             // {US=340.0, EU=280.0}

        // Two-level grouping: region → product → count
        Map<String, Map<String, Long>> matrix = sales.stream()
            .collect(groupingBy(Sale::region, groupingBy(Sale::product, counting())));
        System.out.println(matrix);
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.