Intermediate 30 min read

Model an Employee Directory (Maps)

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

  • Write the Employee wrapper class from the design sketch
  • Write an EmployeeDirectory class holding a Map<String, Employee>
  • Add and look up employees by employee ID

Prerequisites: "Design the Data Structures"

The Employee wrapper class

public class Employee {
    private String employeeId;
    private String name;
    private String department;

    public Employee(String employeeId, String name, String department) {
        this.employeeId = employeeId;
        this.name = name;
        this.department = department;
    }

    public String getEmployeeId() { return employeeId; }
    public String getName() { return name; }
    public String getDepartment() { return department; }
}

This is Module 16's wrapper class pattern combined with Module 10's encapsulation — private fields, set once through the constructor, exposed through controlled getters.

EmployeeDirectory backed by a Map

public class EmployeeDirectory {
    private Map<String, Employee> employeesById = new Map<String, Employee>();

    public void addEmployee(Employee emp) {
        employeesById.put(emp.getEmployeeId(), emp);
    }

    public Employee getEmployee(String employeeId) {
        return employeesById.get(employeeId);
    }

    public Integer getEmployeeCount() {
        return employeesById.size();
    }
}

This is exactly Module 16's Map<Id, sObject> pattern, applied to a custom Employee type instead of a real Salesforce record — one put() per employee, and any lookup afterward is instant, regardless of how many employees the directory holds.

Putting it together

EmployeeDirectory directory = new EmployeeDirectory();

directory.addEmployee(new Employee('E001', 'Amara Nkosi', 'Engineering'));
directory.addEmployee(new Employee('E002', 'Ben Dlamini', 'Sales'));

Employee found = directory.getEmployee('E001');
System.debug(found.getName()); // "Amara Nkosi"
System.debug(directory.getEmployeeCount()); // 2

No looping required to find E001 — the Map inside EmployeeDirectory handles the lookup directly, exactly the performance benefit highlighted back in Module 16's "Maps" lesson.

Exercise

Add a removeEmployee(String employeeId) method to EmployeeDirectory that removes an employee from the map.

Show hint

employeesById.remove(employeeId);

APEX

Model an Employee Directory (Maps) Quiz

1. Why does EmployeeDirectory use a Map instead of a List to store employees?

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 turns the sketch from Lesson 1 into real classes — an Employee wrapper class, and an EmployeeDirectory backed by a Map for instant lookups by ID.