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;
}
public Set<String> getAllDepartments() {— returns a deduplicated set of department names.Set<String> departments = new Set<String>();— an empty set to collect into.for (Employee emp : employeesById.values()) {—.values()returns everyEmployeein the map, ignoring the keys.departments.add(emp.getDepartment());— adding each department to aSetautomatically deduplicates — exactly Module 16's "Sets" lesson, applied directly to real employee data.}— closes the loop.return departments;— returns the unique set.}— closes the method.
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;
}
public Boolean addEmployee(Employee emp) {— now returns aBoolean, exactly the pattern from Module 12's "Add Business Rules" lesson.if (employeesById.containsKey(emp.getEmployeeId())) {—containsKey()checks whether the ID is already taken before adding.System.debug('Employee ID ' + emp.getEmployeeId() + ' already exists.');— a clear reason logged.return false;— rejects the duplicate.}— closes theif.employeesById.put(emp.getEmployeeId(), emp);— without the check above, a secondput()with the same key would silently overwrite the original employee, losing their data entirely.return true;— reports success.}— closes the method.
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.