Combining summingInt with groupingBy for Aggregated Sums
What you'll learn: How to calculate totals for each group by passing summingInt as a downstream collector to groupingBy.
The Core Idea
When you group stream elements by a property, you often want to compute a sum per group rather than just collecting the elements. By using summingInt() as the downstream collector in groupingBy(), you transform the default List of grouped items into an Integer sum for each group.
Think of it like organizing sales data by region: instead of listing every transaction per region, you want the total revenue for each region. That's exactly what this combination delivers.
How It Works
The pattern is:
groupingBy(classifierFunction, summingInt(toIntFunction))
The classifier groups elements into categories, and summingInt adds up values extracted from each element in that category.
Example Scenario
Suppose you have Product objects with a category and price, and you want total sales per category:
List<Product> products = List.of(
new Product("Electronics", 200),
new Product("Electronics", 150),
new Product("Books", 20),
new Product("Books", 15)
);
Map<String, Integer> totalsByCategory = products.stream()
.collect(groupingBy(
Product::getCategory,
summingInt(Product::getPrice)
));
// Result: {Electronics=350, Books=35}
Instead of Map<String, List<Product>>, you get Map<String, Integer> where each integer is the sum of prices in that category.
Key Takeaway: Use groupingBy with summingInt downstream to produce a map of category-to-sum, perfect for aggregated totals like revenue, counts, or weights per group.