Intermediate
20 min read
Sets
By the end of this lesson, you'll be able to:
- Declare and initialize a Set of a specific type
- Explain why a Set automatically prevents duplicate values
- Use a Set to deduplicate a List of values
Prerequisites: Module 15: "Collections: Lists"
A collection that enforces uniqueness
Set<String> uniqueEmails = new Set<String>();
uniqueEmails.add('amara@example.com');
uniqueEmails.add('ben@example.com');
uniqueEmails.add('amara@example.com'); // silently ignored — already present
System.debug(uniqueEmails.size()); // 2, not 3
Set<String> uniqueEmails = new Set<String>();— an emptySetofStringvalues.uniqueEmails.add('amara@example.com');— adds the first email.uniqueEmails.add('ben@example.com');— adds a second.uniqueEmails.add('amara@example.com');— unlikeList(Module 15), adding a value already in aSetdoes nothing — no error, no duplicate, just silently ignored.- (blank line)
System.debug(uniqueEmails.size());— logs2, not3.
This single trait is the whole reason to reach for Set instead of List.
Deduplicating a List with a Set
List<String> industries = new List<String>{'Retail', 'Manufacturing', 'Retail', 'Healthcare', 'Manufacturing'};
Set<String> uniqueIndustries = new Set<String>(industries);
System.debug(uniqueIndustries.size()); // 3
List<String> industries = new List<String>{'Retail', 'Manufacturing', 'Retail', 'Healthcare', 'Manufacturing'};— a list with two repeated values.Set<String> uniqueIndustries = new Set<String>(industries);— passing aListdirectly intonew Set<String>(...)is the fastest way to deduplicate it — every duplicate is automatically dropped, no loop required.- (blank line)
System.debug(uniqueIndustries.size());— logs3— the three unique values.
Checking membership: contains()
Set<String> vipCustomerIds = new Set<String>{'C001', 'C002', 'C003'};
if (vipCustomerIds.contains('C002')) {
System.debug('This is a VIP customer.');
}
Set<String> vipCustomerIds = new Set<String>{'C001', 'C002', 'C003'};— a set of ids.- (blank line)
if (vipCustomerIds.contains('C002')) {—contains()checks whether a value exists in aSet— typically much faster than looping through aListchecking each item one by one, especially as the collection grows large.System.debug('This is a VIP customer.');— runs since'C002'is present.}— closes theif.
Exercise
Given List<String> tags = new List<String>{'urgent', 'billing', 'urgent', 'refund', 'billing'}, build a Set<String> of the unique tags and debug its size.
Show hint
new Set<String>(tags)
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
A Set holds unique values with no guaranteed order — the natural fit whenever "does this exist already?" matters more than position or duplicates.