Real-World Example: Sales Data Aggregation
You'll learn how to combine counting(), summingInt(), and averagingInt() collectors with groupingBy() to analyze sales data by category and extract meaningful business insights.
The Business Scenario
Imagine you're analyzing a company's sales records. Each sale has a product category, quantity sold, and price. You need to answer questions like: "How many sales per category?", "What's the total revenue per category?", and "What's the average sale value per category?"
This is where downstream collectors shine—you can compute multiple statistics simultaneously on grouped data.
Building the Analysis Pipeline
Let's say you have a SaleRecord class with methods getCategory(), getQuantity(), and getPrice(). Here's how you'd analyze sales by category:
// Count sales per category
Map<String, Long> salesCountByCategory =
sales.stream()
.collect(groupingBy(SaleRecord::getCategory, counting()));
// Total revenue per category (quantity × price)
Map<String, Integer> revenueByCategory =
sales.stream()
.collect(groupingBy(
SaleRecord::getCategory,
summingInt(sale -> sale.getQuantity() * sale.getPrice())
));
// Average sale value per category
Map<String, Double> avgSaleByCategory =
sales.stream()
.collect(groupingBy(
SaleRecord::getCategory,
averagingInt(sale -> sale.getQuantity() * sale.getPrice())
));
Why This Matters
Instead of writing nested loops, temporary maps, and manual arithmetic, you declaratively express what you want. The collectors handle the how—accumulating counts, sums, and averages efficiently. Each collector produces a Map<String, Result> where the key is the category and the value is your computed statistic.
Key Takeaway: Combining groupingBy() with counting(), summingInt(), and averagingInt() lets you perform sophisticated data aggregation in a single, readable pipeline—transforming raw sales data into actionable business metrics.