Using averagingInt to Calculate Group Averages
What you'll learn: How to combine averagingInt with groupingBy to compute the average value for each category in your data.
The Core Idea
You've already seen how averagingInt computes the average of all elements in a stream, and how groupingBy separates elements into categories. When you combine them, you get a powerful tool: calculating separate averages for each group.
Think of it like computing average test scores per classroom. Instead of one overall average for the entire school, you get each classroom's average automatically organized in a map.
How It Works
Use averagingInt as the downstream collector inside groupingBy. The result is a Map<K, Double> where each key represents a category, and each value is the average for that group.
Map<String, Double> averagesByDepartment = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.averagingInt(Employee::getSalary)
));
This groups employees by department and computes the average salary for each department.
Practical Example
List<Product> products = Arrays.asList(
new Product("Electronics", 299),
new Product("Electronics", 199),
new Product("Books", 15),
new Product("Books", 25)
);
Map<String, Double> avgPriceByCategory = products.stream()
.collect(Collectors.groupingBy(
Product::getCategory,
Collectors.averagingInt(Product::getPrice)
));
// Result: {Electronics=249.0, Books=20.0}
Each category appears once in the map with its computed average price.
Why This Matters
Instead of manually looping through categories, filtering, and calculating averages yourself, this one-liner does it all. It's declarative, readable, and efficient.
Key Takeaway: Combine averagingInt with groupingBy to automatically compute average values for each category, producing a clean Map<Category, Double> result without manual iteration.