Remove duplicate emails with a Set
Write Apex · 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('[email protected]');
seen.add('[email protected]');
System.debug(seen.size());
This prints 1.
Gotcha. A Set cares about letter case, but == does not. '[email protected]' and '[email protected]' 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>{ '[email protected]', '[email protected]', '[email protected]' })→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
[email protected]and[email protected]count 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>{ '[email protected]', '[email protected]', null, '[email protected]' };
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.