00:00

Summing and Averaging Collectors in Java

Last updated:

The summing and averaging collectors are static methods of java.util.stream.Collectors, available since Java 8: summingInt(), summingLong(), summingDouble(), averagingInt(), averagingLong() and averagingDouble(). Each takes a function that extracts a number from an element and returns a Collector that adds the numbers or computes their arithmetic mean.

They shine as downstream collectors, for totals and averages per group. This tutorial covers their signatures and result types, empty inputs, floating-point accuracy, and when mapToInt().sum() is simpler.

1. Syntax and Method Signatures

Collectors.java (API)
// java.util.stream.Collectors (Java 8)
static <T> Collector<T, ?, Integer> summingInt(ToIntFunction<? super T> mapper)
static <T> Collector<T, ?, Long>    summingLong(ToLongFunction<? super T> mapper)
static <T> Collector<T, ?, Double>  summingDouble(ToDoubleFunction<? super T> mapper)

static <T> Collector<T, ?, Double>  averagingInt(ToIntFunction<? super T> mapper)
static <T> Collector<T, ?, Double>  averagingLong(ToLongFunction<? super T> mapper)
static <T> Collector<T, ?, Double>  averagingDouble(ToDoubleFunction<? super T> mapper)

The mapper is a primitive-returning function such as ToIntFunction, so no boxing happens while adding. Sums keep the element type (Integer, Long, Double); averages are always Double.

2. How Summing and Averaging Work

Each collector extracts a primitive value per element and keeps running totals: a sum, and for averages also a count. At the end, an averaging collector divides the sum by the count. For an empty input, sums return 0 and averages return 0.0, not NaN and not an empty Optional.

summingDouble() and averagingDouble() use a compensated summation algorithm to reduce rounding error, so their results can differ very slightly from a naive loop. summingInt() can overflow just like int addition; use summingLong() for large totals.

Summing and averaging the same group Salaries of 50000, 70000 and 90000 in one department. summingInt adds them to 210000. averagingInt divides the sum by the count of 3 and returns 70000.0 as a Double. INPUT COLLECTOR RESULT Engineering 50k, 70k, 90k summingInt(salary) 210000 (Integer) Engineering 50k, 70k, 90k averagingInt(salary) 70000.0 (Double) Empty group no elements averagingInt 0.0
Figure 1: Sums keep the integer type; averages always return a Double. An empty input gives 0 for sums and 0.0 for averages.

3. Java Examples

Example 1: Total and average per department (Java 16+)

Report the salary bill and average salary of each department.

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

public class SalaryByDepartment {

    record Employee(String name, String dept, int salary) { }

    public static void main(String[] args) {
        List<Employee> staff = List.of(
                new Employee("Asha", "Eng", 50_000), new Employee("Ben", "Eng", 70_000),
                new Employee("Cy", "Eng", 90_000), new Employee("Dee", "Ops", 45_000), new Employee("Eli", "Ops", 52_000));

        Map<String, Integer> totals = staff.stream()
                .collect(Collectors.groupingBy(Employee::dept, TreeMap::new, Collectors.summingInt(Employee::salary)));
        Map<String, Double> averages = staff.stream()
                .collect(Collectors.groupingBy(Employee::dept, TreeMap::new, Collectors.averagingInt(Employee::salary)));

        totals.forEach((dept, total) ->
                System.out.println(dept + ": total " + total + ", average " + averages.get(dept)));
    }
}
Output
Eng: total 210000, average 70000.0
Ops: total 97000, average 48500.0

How it works: summingInt() returns Integer totals, while averagingInt() returns Double averages, even when the average is a whole number.

Example 2: Sums of long and double values (Java 16+)

Total the bytes downloaded per user (which can exceed the int range) and the average session length in minutes.

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

public class UsageTotals {

    record Session(String user, long bytes, double minutes) { }

    public static void main(String[] args) {
        List<Session> sessions = List.of(
                new Session("u1", 3_000_000_000L, 42.5), new Session("u2", 750_000_000L, 12.0),
                new Session("u1", 1_500_000_000L, 18.25));

        Map<String, Long> bytes = sessions.stream()
                .collect(Collectors.groupingBy(Session::user, TreeMap::new, Collectors.summingLong(Session::bytes)));
        Map<String, Double> avgMinutes = sessions.stream()
                .collect(Collectors.groupingBy(Session::user, TreeMap::new, Collectors.averagingDouble(Session::minutes)));

        System.out.println("Bytes:       " + bytes);
        System.out.println("Avg minutes: " + avgMinutes);
    }
}
Output
Bytes:       {u1=4500000000, u2=750000000}
Avg minutes: {u1=30.375, u2=12.0}

How it works: 4.5 billion bytes would overflow an int, so summingLong() is required. averagingDouble() works with the fractional minutes.

Example 3: Empty input (Java 16+)

Compute the average rating of a product that has no reviews yet, with a collector and with IntStream.average().

EmptyAverage.java
import java.util.List;
import java.util.stream.Collectors;

public class EmptyAverage {

    record Review(String user, int stars) { }

    public static void main(String[] args) {
        List<Review> reviews = List.of();

        Double viaCollector = reviews.stream().collect(Collectors.averagingInt(Review::stars));
        boolean hasAverage = reviews.stream().mapToInt(Review::stars).average().isPresent();

        System.out.println("averagingInt on no reviews: " + viaCollector);
        System.out.println("IntStream.average() present? " + hasAverage);
    }
}
Output
averagingInt on no reviews: 0.0
IntStream.average() present? false

How it works: The collector reports 0.0 for no data, which a page might show as "0 stars". IntStream.average() returns an empty OptionalDouble, which lets you show "no reviews yet" instead. Choose based on whether "no data" needs to be visible.

Example 4: When a primitive stream is simpler (Java 16+)

Compute the total value of a single cart, without grouping.

SingleTotal.java
import java.util.List;
import java.util.stream.Collectors;

public class SingleTotal {

    record Line(String item, int qty, int price) { }

    public static void main(String[] args) {
        List<Line> cart = List.of(new Line("Pen", 4, 25), new Line("Pad", 2, 60), new Line("Clip", 10, 3));

        int viaCollector = cart.stream().collect(Collectors.summingInt(l -> l.qty() * l.price()));
        int viaIntStream = cart.stream().mapToInt(l -> l.qty() * l.price()).sum();

        System.out.println(viaCollector + " = " + viaIntStream);
    }
}
Output
250 = 250

How it works: For one total, mapToInt(...).sum() is shorter and returns a primitive. Use the collectors where a collector is required, for example inside groupingBy() or partitioningBy().

4. Real-World Use Cases

  • Finance: revenue per region, expenses per category, average order value per customer.
  • HR: salary bill and average salary per department.
  • Operations: average delivery time per courier, total units per warehouse.
  • Analytics: average rating per product, total minutes per user.

5. Important Points

  • Averages are Double, even for averagingInt().
  • Empty input: sums are 0, averages are 0.0; there is no empty marker.
  • Overflow: summingInt() overflows silently; use summingLong() for large totals.
  • Money: double is approximate; for currency, sum long paise or use BigDecimal with reduce().
  • Nulls: the mapper must not unbox a null; filter first.

6. Collectors vs Primitive Streams

NeedCollectorPrimitive stream alternative
Total of ints per groupsummingInt()-
Total of ints, one valuesummingInt()mapToInt(f).sum()
Average per groupaveragingInt() (0.0 if empty)-
Average, one valueaveragingInt()mapToInt(f).average() (empty OptionalDouble)
Count, sum, min, max, averagesummarizingInt()mapToInt(f).summaryStatistics()

When you need several statistics per group, summarizingInt() computes them in one pass.

7. Common Mistakes and Best Practices

Summing money as double

MoneyRounding.java
import java.util.List;
import java.util.stream.Collectors;

public class MoneyRounding {

    public static void main(String[] args) {
        List<Double> payments = List.of(0.1, 0.2, 0.3);
        List<Long> paise = List.of(10L, 20L, 30L);

        double asDouble = payments.stream().mapToDouble(Double::doubleValue).reduce(0, Double::sum);
        long asPaise = paise.stream().collect(Collectors.summingLong(Long::longValue));

        System.out.println("Plain double sum: " + asDouble);
        System.out.println("Paise sum:        " + asPaise + " (= Rs " + asPaise / 100.0 + ")");
    }
}
Output
Plain double sum: 0.6000000000000001
Paise sum:        60 (= Rs 0.6)

Floating-point values cannot represent most decimal fractions exactly. Store money as whole paise in a long, or use BigDecimal.

Other mistakes to avoid

  • Assigning an average to Integer. It is a Double.
  • Treating 0.0 as a real average when there was no data.
  • Running two passes for sum and average. Use summarizingInt().

8. Summary

  • summingXxx() adds extracted numbers; averagingXxx() returns their mean as a Double.
  • Empty inputs give 0 and 0.0.
  • They are most useful as downstream collectors per group.
  • Watch for int overflow and avoid double for money.

9. References