Remove duplicate emails with a Set
Apex basics · Beginner · 12 min · Runs in your Salesforce Developer org · Free
Scenario. Marketing imported a signup list. Some people signed up twice, once in capitals, and some rows have no email at all.
Write a method that counts different emails with a Set<String>, ignoring letter case and skipping empty entries.
What you will learn
A Set<String> keeps each value only once. add skips a value that is already there, contains checks for one, and size counts them.
Set<String> seen = new Set<String>();
seen.add('ana@acme.com');
seen.add('ana@acme.com');
System.debug(seen.size());
This prints 1.
Gotcha. A Set cares about letter case, but == does not. 'Ana@acme.com' and 'ana@acme.com' are two Set entries, so call toLowerCase() before you add.
The task
Write a method uniqueEmailCount(List<String> emails) that returns how many different emails the list holds.
Examples:
uniqueEmailCount(new List<String>{ 'a@x.com', 'A@x.com', 'b@x.com' })→2uniqueEmailCount(new List<String>())→0nulland''entries are skipped, so the starter'ssignupslist printsUnique signups: 2
Requirements:
- Use a
Set<String>to keep each email once. - Lowercase each email before you add it, so
A@x.comanda@x.comcount once. - Skip entries that are null or blank.
- Keep the method's name and input, and the line that prints
Unique signups:. The grader also calls your method with other lists, some of them hidden.
Starter code
Integer uniqueEmailCount(List<String> emails) {
return null;
}
List<String> signups = new List<String>{ 'ana@acme.com', 'ANA@acme.com', null, 'raj@acme.com' };
System.debug('Unique signups: ' + uniqueEmailCount(signups));
When it passes
Your method counts each email once whatever its letter case, skips null and blank entries, and returns 0 for an empty list.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.