Summing and Averaging Collectors in Java
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
// 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.
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.
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)));
}
}
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.
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);
}
}
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().
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);
}
}
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.
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);
}
}
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 foraveragingInt(). - Empty input: sums are 0, averages are 0.0; there is no empty marker.
- Overflow:
summingInt()overflows silently; usesummingLong()for large totals. - Money:
doubleis approximate; for currency, sumlongpaise or useBigDecimalwithreduce(). - Nulls: the mapper must not unbox a
null; filter first.
6. Collectors vs Primitive Streams
| Need | Collector | Primitive stream alternative |
|---|---|---|
| Total of ints per group | summingInt() | - |
| Total of ints, one value | summingInt() | mapToInt(f).sum() |
| Average per group | averagingInt() (0.0 if empty) | - |
| Average, one value | averagingInt() | mapToInt(f).average() (empty OptionalDouble) |
| Count, sum, min, max, average | summarizingInt() | 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
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 + ")");
}
}
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 aDouble. - 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 aDouble.- Empty inputs give 0 and 0.0.
- They are most useful as downstream collectors per group.
- Watch for
intoverflow and avoiddoublefor money.
9. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between summingInt() and averagingInt()?
summingInt() adds the int values extracted from each element and returns an Integer. averagingInt() returns their arithmetic mean as a Double.
Q2. What do averaging collectors return for an empty stream?
They return 0.0. If you need to distinguish no data from a real average of zero, use mapToInt(...).average(), which returns an empty OptionalDouble.
Q3. Why does averagingInt() return a Double?
The mean of integers is usually not an integer, for example the average of 1 and 2 is 1.5, so all averaging collectors return Double.
Q4. Can summingInt() overflow?
Yes. It adds int values and the total is an int, so very large sums wrap around silently. Use summingLong() for large totals.
Q5. Should I use summingInt() or mapToInt().sum()?
Use mapToInt().sum() for a single total on a stream. Use summingInt() where a collector is needed, such as inside groupingBy() or partitioningBy().