00:00

Group Objects Using Java Streams

Last updated:

Grouping objects with Java streams means splitting a list into buckets by some property and, usually, summarising each bucket. The tool is Collectors.groupingBy() (Java 8), combined with downstream collectors such as counting(), summingInt(), mapping() and maxBy().

This page works through practical grouping tasks: by one field, by a computed key, by several fields with a composite key, with sorted keys, and with several statistics per group. The method itself is explained in Collectors.groupingBy().

1. Grouping Recipes

Grouping recipes
// one field -> list of objects
Map<String, List<Order>> byCity = orders.stream().collect(groupingBy(Order::city));

// one field -> summary per group
Map<String, Integer> revenue = orders.stream().collect(groupingBy(Order::city, summingInt(Order::amount)));

// sorted keys + summary
Map<String, Long> counts = orders.stream().collect(groupingBy(Order::city, TreeMap::new, counting()));

// several fields -> composite key
record CityMonth(String city, YearMonth month) { }
Map<CityMonth, Long> perCityMonth = orders.stream()
        .collect(groupingBy(o -> new CityMonth(o.city(), YearMonth.from(o.date())), counting()));

2. How Grouping Works

groupingBy() applies the classifier to every element, creates a container per distinct key and feeds each element to its group's downstream collector. Any object with correct equals() and hashCode() can be a key: a String, an enum, a YearMonth, or a record that combines several fields.

Grouping orders by a composite key Four orders: Pune in January, Pune in January, Pune in February and Goa in January. groupingBy with a CityMonth record key creates three groups: Pune January with two orders, Pune February with one, and Goa January with one. ORDER KEY: (city, month) GROUP O1 Pune, 2026-01-03 (Pune, 2026-01) Pune Jan: 2 orders O2 Pune, 2026-01-19 (Pune, 2026-01) same group O3 Pune, 2026-02-02 (Pune, 2026-02) Pune Feb: 1 order O4 Goa, 2026-01-11 (Goa, 2026-01) Goa Jan: 1 order
Figure 1: A record holding both fields is a clean composite key: it has value-based equals() and hashCode() for free.

3. Real-World Examples

Example 1: Group and summarise by one field (Java 16+)

For a sales team, show each salesperson's number of deals, total value and largest deal.

DealsPerSalesperson.java
import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class DealsPerSalesperson {

    record Deal(String owner, String client, int value) { }

    public static void main(String[] args) {
        List<Deal> deals = List.of(
                new Deal("Nisha", "Acme", 120_000), new Deal("Arjun", "Globex", 45_000),
                new Deal("Nisha", "Initech", 60_000), new Deal("Arjun", "Umbra", 210_000),
                new Deal("Kabir", "Vertex", 80_000));

        Map<String, IntSummaryStatistics> stats = deals.stream()
                .collect(Collectors.groupingBy(Deal::owner, TreeMap::new, Collectors.summarizingInt(Deal::value)));

        stats.forEach((owner, s) -> System.out.printf("%-6s deals=%d total=%,d largest=%,d%n",
                owner, s.getCount(), s.getSum(), s.getMax()));
    }
}
Output
Arjun  deals=2 total=255,000 largest=210,000
Kabir  deals=1 total=80,000 largest=80,000
Nisha  deals=2 total=180,000 largest=120,000

How it works: summarizingInt() gives count, total and maximum per salesperson in one pass, and TreeMap::new sorts the names.

Example 2: Group by a computed key (Java 16+)

Bucket customers by age band for a marketing report.

AgeBands.java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class AgeBands {

    record Customer(String name, int age) { }

    static String band(int age) {
        if (age < 25) return "18-24";
        if (age < 35) return "25-34";
        if (age < 50) return "35-49";
        return "50+";
    }

    public static void main(String[] args) {
        List<Customer> customers = List.of(
                new Customer("Ana", 22), new Customer("Bo", 31), new Customer("Cy", 47), new Customer("Di", 29),
                new Customer("Ed", 63), new Customer("Fa", 24));

        Map<String, List<String>> byBand = customers.stream()
                .collect(Collectors.groupingBy(c -> band(c.age()), TreeMap::new,
                        Collectors.mapping(Customer::name, Collectors.toList())));

        System.out.println(byBand);
    }
}
Output
{18-24=[Ana, Fa], 25-34=[Bo, Di], 35-49=[Cy], 50+=[Ed]}

How it works: The classifier can compute anything; here a helper method maps an age to a band label. String labels sort correctly here because they start with digits.

Example 3: Group by several fields with a record key (Java 16+)

Count orders per city per month.

OrdersPerCityMonth.java
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class OrdersPerCityMonth {

    record Order(String id, String city, LocalDate date) { }
    record CityMonth(String city, YearMonth month) { }

    public static void main(String[] args) {
        List<Order> orders = List.of(
                new Order("O1", "Pune", LocalDate.of(2026, 1, 3)), new Order("O2", "Pune", LocalDate.of(2026, 1, 19)),
                new Order("O3", "Pune", LocalDate.of(2026, 2, 2)), new Order("O4", "Goa", LocalDate.of(2026, 1, 11)));

        Map<CityMonth, Long> counts = orders.stream()
                .collect(Collectors.groupingBy(
                        o -> new CityMonth(o.city(), YearMonth.from(o.date())),
                        () -> new TreeMap<>(Comparator.comparing(CityMonth::city).thenComparing(CityMonth::month)),
                        Collectors.counting()));

        counts.forEach((k, n) -> System.out.println(k.city() + " " + k.month() + ": " + n));
    }
}
Output
Goa 2026-01: 1
Pune 2026-01: 2
Pune 2026-02: 1

How it works: A record combines the two fields into one key with correct equals() and hashCode(). A TreeMap with a comparator sorts the composite keys. This is usually clearer than nesting two groupingBy() calls.

Example 4: The best item per group (Java 16+)

Find the highest-rated restaurant in each neighbourhood.

BestPerNeighbourhood.java
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class BestPerNeighbourhood {

    record Restaurant(String name, String area, double rating) { }

    public static void main(String[] args) {
        List<Restaurant> list = List.of(
                new Restaurant("Spice Route", "Indiranagar", 4.4), new Restaurant("Toit Bites", "Indiranagar", 4.6),
                new Restaurant("Dosa Den", "Jayanagar", 4.5), new Restaurant("Chai Point", "Jayanagar", 4.1));

        Map<String, String> best = list.stream()
                .collect(Collectors.groupingBy(Restaurant::area, TreeMap::new,
                        Collectors.collectingAndThen(
                                Collectors.maxBy(Comparator.comparingDouble(Restaurant::rating)),
                                r -> r.map(Restaurant::name).orElse("-"))));

        System.out.println(best);
    }
}
Output
{Indiranagar=Toit Bites, Jayanagar=Dosa Den}

How it works: maxBy() finds the best restaurant per group and collectingAndThen() turns the Optional into a name.

4. Real-World Use Cases

  • Sales and finance: totals and counts per salesperson, region, month or product.
  • Marketing: customers per age band, city or acquisition channel.
  • Operations: shipments per warehouse per day.
  • Dashboards: chart data grouped by a time bucket.

5. Important Points

  • Key quality: keys must have correct equals() and hashCode(); records do.
  • Null keys throw NullPointerException; map them to a placeholder.
  • Key order: use TreeMap::new or LinkedHashMap::new when order matters.
  • Missing groups: only keys present in the data appear.
  • Memory: prefer summarising downstream collectors over storing lists of objects.

6. Which Collector for Which Result

NeedCollector
Objects per keygroupingBy(key)
Count per keygroupingBy(key, counting())
Total per keygroupingBy(key, summingInt(f))
Several statistics per keygroupingBy(key, summarizingInt(f))
One field per keygroupingBy(key, mapping(f, toList()))
Best item per keygroupingBy(key, maxBy(c))
Two groups (yes/no)partitioningBy(p)

See also partitioningBy() and summarizingInt().

7. Common Mistakes and Best Practices

Nesting groupingBy too deeply

Three nested maps are hard to read and to iterate. A record composite key, as in Example 3, keeps one flat map.

Grouping and then streaming each group again

Extra pass
byCity.forEach((city, list) -> System.out.println(city + " " + list.stream().mapToInt(Order::amount).sum()));

Use groupingBy(Order::city, summingInt(Order::amount)) to compute the totals while grouping.

Other mistakes to avoid

  • Using a mutable object as a key and changing it later.
  • Expecting sorted keys from the default HashMap.
  • Forgetting null keys in imported data.

8. Summary

  • groupingBy() buckets objects by a key; downstream collectors summarise each bucket.
  • Use computed keys for bands and records for multi-field keys.
  • Sort keys with a TreeMap; handle null keys.
  • Summarise while grouping instead of streaming the groups again.

9. References