The averagingInt, averagingLong, and averagingDouble Collectors
What you'll learn: How to compute the arithmetic mean of numeric stream elements using specialized averaging collectors that always return a Double result.
Understanding Averaging Collectors
While summingInt, summingLong, and summingDouble give you totals, the averaging collectors automatically calculate the mean (average) of your numeric values. Think of them as built-in calculators that divide the sum by the count for you.
These three collectors work similarly to their summing counterparts:
Collectors.averagingInt()accepts aToIntFunctionmapperCollectors.averagingLong()accepts aToLongFunctionmapperCollectors.averagingDouble()accepts aToDoubleFunctionmapper
Key Characteristics
Always returns Double: Regardless of which variant you use, the result is always Double. Even averagingInt returns Double, not int, because averages often have fractional parts.
Handles empty streams gracefully: If the stream is empty, the result is 0.0 (not an Optional).
Typical Usage
Like summingInt, you'll often use these with groupingBy as downstream collectors:
// Average price per category
Map<String, Double> avgPriceByCategory = products.stream()
.collect(groupingBy(
Product::getCategory,
averagingDouble(Product::getPrice)
));
// Average age by department
Map<String, Double> avgAgeByDept = employees.stream()
.collect(groupingBy(
Employee::getDepartment,
averagingInt(Employee::getAge)
));
These collectors are particularly useful for statistical analysis and reporting where you need per-group averages rather than overall totals.
Key Takeaway: The averaging collectors (averagingInt, averagingLong, averagingDouble) compute arithmetic means of numeric values and always return Double, making them ideal for statistical aggregations in grouped data.