Intermediate 30 min read

Generate Reports from Collections

By the end of this lesson, you'll be able to:

  • Build a Map<String, Integer> reporting headcount per department
  • Use a nested collection to group employees by department
  • Explain why generating reports from existing collections avoids a second data pass

Prerequisites: "Deduplicate and Validate (Sets)"

Headcount per department

public Map<String, Integer> getHeadcountByDepartment() {
    Map<String, Integer> headcount = new Map<String, Integer>();

    for (Employee emp : employeesById.values()) {
        String dept = emp.getDepartment();
        if (! headcount.containsKey(dept)) {
            headcount.put(dept, 0);
        }
        headcount.put(dept, headcount.get(dept) + 1);
    }

    return headcount;
}

For each employee, this either starts a department's count at 0 (the first time it's seen) or increments the existing count — a single pass over every employee produces a complete report, no separate query or loop per department needed.

Grouping employees by department (nested collections)

public Map<String, List<Employee>> getEmployeesByDepartment() {
    Map<String, List<Employee>> grouped = new Map<String, List<Employee>>();

    for (Employee emp : employeesById.values()) {
        String dept = emp.getDepartment();
        if (! grouped.containsKey(dept)) {
            grouped.put(dept, new List<Employee>());
        }
        grouped.get(dept).add(emp);
    }

    return grouped;
}

This is Module 16's "Nested Collections" lesson — a Map<String, List<Employee>> — put to real use: every department's full employee list, generated from the same underlying data as the headcount report above, no re-querying needed.

Why generate reports from existing data

Both reports loop over employeesById.values() once and build their result in memory — no second database query, no re-fetching data that's already sitting in the directory. This mirrors the bulkification instinct from Module 7: do the necessary work in one clean pass over data you already have, rather than repeating expensive operations per report.

Exercise

Add a method getTotalHeadcount() that returns the sum of every department's count from getHeadcountByDepartment().

Show hint

Loop over headcount.values() and sum them.

APEX

Generate Reports from Collections Quiz

1. Why do these report methods loop over the existing employeesById map instead of re-fetching data?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

This lesson generates two useful reports directly from the existing employee data: headcount per department, and a full grouping of employees by department, using nested collections from Module 16.