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
Unlike List (Module 15), adding a value already in a Set does nothing — no error, no duplicate, just silently ignored. 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
Passing a List directly into new Set<String>(...) is the fastest way to deduplicate it — every duplicate is automatically dropped, no loop required.
Checking membership: contains()
Set<String> vipCustomerIds = new Set<String>{'C001', 'C002', 'C003'};
if (vipCustomerIds.contains('C002')) {
System.debug('This is a VIP customer.');
}
contains() checks whether a value exists in a Set — and it's typically much faster than looping through a List checking each item one by one, especially as the collection grows large.
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.