Video in progress

After groupingBy, how do you get a sum, an average, or just a list of one field for each group?

The second argument of groupingBy is a downstream collector. Collectors like summingLong, averagingDouble, mapping, maxBy, toSet and collectingAndThen work inside each group, so you don't need separate processing afterward.

📖 Answer

A few reports from a list of orders:

record Order(String customer, String city, long amount, Status status) {}

// total amount per customer
Map<String, Long> totalByCustomer = orders.stream()
        .collect(groupingBy(Order::customer, summingLong(Order::amount)));

// average receipt per city
Map<String, Double> avgByCity = orders.stream()
        .collect(groupingBy(Order::city, averagingLong(Order::amount)));

// set of customers per city (just the name, not the object)
Map<String, Set<String>> customersByCity = orders.stream()
        .collect(groupingBy(Order::city, mapping(Order::customer, toSet())));

// the largest order per status, without Optional
Map<Status, Order> biggest = orders.stream()
        .collect(groupingBy(Order::status,
                collectingAndThen(maxBy(comparingLong(Order::amount)), Optional::get)));

In the last example Optional::get is safe, because groupingBy doesn't create empty groups: every group has at least one element.

Two-level grouping is possible too: groupingBy(Order::city, groupingBy(Order::status, counting())) gives a Map<String, Map<Status, Long>>. If you end up needing a third level, it gets hard to read, and I usually build a separate record key: groupingBy(o -> new Key(o.city(), o.status())).

Java 9 added filtering and flatMapping. The benefit of filtering is that the filter works after grouping, so all keys are kept, and a group with no matching element stays there empty.