Group Objects Using Java Streams
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
// 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.
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.
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()));
}
}
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.
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);
}
}
{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.
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));
}
}
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.
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);
}
}
{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()andhashCode(); records do. - Null keys throw
NullPointerException; map them to a placeholder. - Key order: use
TreeMap::neworLinkedHashMap::newwhen 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
| Need | Collector |
|---|---|
| Objects per key | groupingBy(key) |
| Count per key | groupingBy(key, counting()) |
| Total per key | groupingBy(key, summingInt(f)) |
| Several statistics per key | groupingBy(key, summarizingInt(f)) |
| One field per key | groupingBy(key, mapping(f, toList())) |
| Best item per key | groupingBy(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
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
Frequently Asked Questions (FAQ)
Q1. How do I group a list of objects by a field in Java 8?
Use list.stream().collect(Collectors.groupingBy(Item::field)). It returns a Map from each field value to the list of objects with that value.
Q2. How do I group by multiple fields?
Create a record with the fields, for example record CityMonth(String city, YearMonth month), and group by a lambda that builds that record. Records provide the equals() and hashCode() a key needs.
Q3. How do I get a count or sum per group?
Pass a downstream collector: groupingBy(key, Collectors.counting()) or groupingBy(key, Collectors.summingInt(Item::amount)).
Q4. How do I keep the group keys sorted?
Use the three-argument groupingBy() with TreeMap::new, or a TreeMap with a comparator for composite keys.
Q5. Why does groupingBy() throw NullPointerException?
One of the elements produced a null key. Map null values to a placeholder such as "unknown" in the classifier.