Course contentsShow
← Java
Lesson 1573 of 2,87034. Collectors in DepthFree lesson

Summing, Averaging, and Statistics per Group

Combine groupingBy with summingInt, averagingDouble, or summarizingInt to compute aggregates per group.

Summing, Averaging, and Statistics per Group

What you'll learn: How to calculate numeric aggregates (sums, averages, and full statistics) for each group when using groupingBy.

The Core Idea

You've already learned to group elements and count them per group. Now you can go further—computing numeric summaries for each group by combining groupingBy with specialized downstream collectors like summingInt, averagingDouble, or summarizingInt.

Think of it like organizing sales data by region, then automatically calculating total revenue, average sale price, or complete statistics (min, max, average, count, sum) for each region—all in one pass through your data.

How It Works

Instead of using counting() as the downstream collector, you use:

  • summingInt() / summingLong() / summingDouble() — calculates the sum of a numeric property per group
  • averagingInt() / averagingLong() / averagingDouble() — calculates the average per group
  • summarizingInt() / summarizingLong() / summarizingDouble() — provides full statistics (count, sum, min, average, max) per group

These downstream collectors extract a numeric value from each element using a mapper function, then aggregate those values within each group.

// Sum salaries by department
Map<String, Integer> salaryByDept = employees.stream()
    .collect(groupingBy(
        Employee::getDepartment,
        summingInt(Employee::getSalary)
    ));

// Average age by city
Map<String, Double> avgAgeByCity = people.stream()
    .collect(groupingBy(
        Person::getCity,
        averagingDouble(Person::getAge)
    ));

// Full statistics of scores by team
Map<String, IntSummaryStatistics> statsByTeam = players.stream()
    .collect(groupingBy(
        Player::getTeam,
        summarizingInt(Player::getScore)
    ));

Key Takeaway: Combine groupingBy with numeric downstream collectors (summingInt, averagingDouble, summarizingInt, etc.) to compute aggregate statistics for each group in a single, expressive pipeline.