Deduplicate and Validate (Sets)
By the end of this lesson, you'll be able to:
- Use a Set to list every unique department across all employees
- Reject an employee with a duplicate employee ID before adding
- Explain why validation belongs inside addEmployee, not scattered across callers
Prerequisites: "Model an Employee Directory (Maps)"
Listing unique departments
public Set<String> getAllDepartments() {
Set<String> departments = new Set<String>();
for (Employee emp : employeesById.values()) {
departments.add(emp.getDepartment());
}
return departments;
}
employeesById.values() returns every Employee in the map (ignoring the keys); looping over them and adding each department to a Set automatically deduplicates — exactly Module 16's "Sets" lesson, applied directly to real employee data.
Rejecting a duplicate employee ID
public Boolean addEmployee(Employee emp) {
if (employeesById.containsKey(emp.getEmployeeId())) {
System.debug('Employee ID ' + emp.getEmployeeId() + ' already exists.');
return false;
}
employeesById.put(emp.getEmployeeId(), emp);
return true;
}
containsKey() checks whether the ID is already taken before adding — without this check, a second put() with the same key would silently overwrite the original employee, losing their data entirely. addEmployee now returns a Boolean, exactly the pattern from Module 12's "Add Business Rules" lesson.
Why this validation lives inside addEmployee
It would be possible to check for duplicates separately, everywhere addEmployee gets called — but exactly like Module 12's CourseRoster.enroll(), that means every caller has to remember to repeat the check, and any caller that forgets creates a silently corrupted directory. Putting the rule inside addEmployee itself enforces it everywhere, automatically.
Exercise
Add a method hasEmployeesInDepartment(String department) that returns true if any employee belongs to that department, using getAllDepartments().
Show hint
return getAllDepartments().contains(department);
Deduplicate and Validate (Sets) Quiz
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 adds two Set-backed capabilities: listing every unique department, and rejecting a duplicate employee ID before it corrupts the directory.