Course contentsShow
← Java
Lesson 1606 of 2,87034. Collectors in DepthFree lesson

Practical Examples: Multi-Level Aggregations

Work through real-world scenarios using reducing and downstream collectors for nested grouping, counting, and summarizing.

Practical Examples: Multi-Level Aggregations

You'll learn how to combine everything you know about downstream collectors to solve complex, real-world data aggregation problems with nested grouping and summarization.

The Real-World Challenge

Imagine analyzing employee data: you need to group by department, then by job title within each department, and finally count employees or calculate average salaries at each level. This requires multi-level aggregations—chaining groupingBy, downstream collectors like mapping, filtering, and terminal collectors like counting() or averagingDouble().

Building Complex Aggregations Layer by Layer

The pattern is straightforward: each level of nesting adds another groupingBy with a downstream collector. The innermost collector performs the final aggregation (counting, summing, averaging).

Example 1: Department → Job Title → Count

Map<String, Map<String, Long>> deptJobCount = employees.stream()
    .collect(groupingBy(
        Employee::getDepartment,
        groupingBy(
            Employee::getJobTitle,
            counting()
        )
    ));
// Result: {"Engineering": {"Developer": 15, "Manager": 3}, ...}

Example 2: Region → Department → Average Salary

Map<String, Map<String, Double>> regionDeptAvgSalary = employees.stream()
    .collect(groupingBy(
        Employee::getRegion,
        groupingBy(
            Employee::getDepartment,
            averagingDouble(Employee::getSalary)
        )
    ));

Example 3: Adding Filtering and Mapping

Filter senior employees, map to their bonus, then sum by department:

Map<String, Double> deptSeniorBonusTotal = employees.stream()
    .collect(groupingBy(
        Employee::getDepartment,
        filtering(
            emp -> emp.getYearsExperience() > 5,
            summingDouble(Employee::getBonus)
        )
    ));

Think of It Like Nested Folders

Each groupingBy creates a folder (map key). Downstream collectors determine what goes inside that folder—another set of folders, a count, a list, or a computed value.

Key Takeaway:
Multi-level aggregations combine nested groupingBy with downstream collectors to transform complex data into hierarchical summaries—the foundation of real-world reporting and analytics.