Sub topic 4
Sets: unique values
This chapter assumes you know basic Apex syntax, how to read a List, and what a SOQL bind variable is. It covers what a Set guarantees, how to create one, and the errors that most often catch developers off guard. The next chapter covers the full method list and set algebra, so only add, contains, and size appear here.
What a Set guarantees
A Set<T> is a collection of elements of type T with two properties:
- Every element is unique. Adding a value that is already present changes nothing.
- There is no index and no reliable order. You cannot write
mySet[0]ormySet.get(0), and the order you iterate in is not something your code can depend on.
A Set is built for one question: "is this value in the collection?" Its contains check does not scan from the start the way a search of a List does, so it stays fast as the collection grows. The set therefore suits two jobs: removing duplicates and testing membership.
| Property | List | Set |
|---|---|---|
| Duplicates allowed | Yes | No |
| Access by index | Yes | No |
| Order you can rely on | Insertion order | None |
| Membership test | Scans the elements | Direct lookup |
Creating a Set
You can create a set empty, with a literal initializer, or from another collection.
Set<String> empty = new Set<String>();
Set<String> tags = new Set<String>{'apex', 'soql'};
List<String> emails = new List<String>{'[email protected]', '[email protected]', '[email protected]'};
Set<String> uniqueEmails = new Set<String>(emails);
System.debug(tags.size()); // 2
System.debug(uniqueEmails.size()); // 2The third form is the usual way to remove duplicates. Pass any List or Set of the same element type to the constructor, and duplicates are dropped as the set is built. If you need a List back afterwards, pass the set to a list constructor: new List<String>(uniqueEmails). That list has no meaningful order.
How add reports duplicates
add returns a Boolean. It returns true if the element was new and false if the set already contained it.
Set<String> tags = new Set<String>{'apex', 'soql'};
Boolean addedAgain = tags.add('apex'); // false, already present
Boolean addedNew = tags.add('trigger'); // true
System.debug(tags.size()); // 3
System.debug(tags.contains('soql')); // trueYou can use the return value to detect repeats in a single pass, without a separate contains call:
List<String> codes = new List<String>{'A1', 'B2', 'A1', 'C3', 'B2'};
Set<String> seen = new Set<String>();
Set<String> repeated = new Set<String>();
for (String code : codes) {
if (!seen.add(code)) {
repeated.add(code);
}
}
System.debug(repeated.size()); // 2Which types can go in a Set
A set can hold primitives such as String, Integer, Id, and Date. It can also hold sObjects, and other collections. Primitive element types behave as you would expect, with a few details worth knowing.
Strings are case-sensitive
'Apex' and 'apex' are different elements. When the data comes from users or external systems and case should not matter, normalize before adding.
Set<String> domains = new Set<String>();
List<String> raw = new List<String>{'Example.com', 'example.COM', 'other.org'};
for (String d : raw) {
if (String.isNotBlank(d)) {
domains.add(d.toLowerCase());
}
}
System.debug(domains.size()); // 2The isNotBlank check matters because calling toLowerCase() on a null string throws a NullPointerException.
Null is a valid element
A set can contain null as one of its elements. That is easy to miss when you collect lookup fields such as AccountId, which is null on a contact with no account. The null then ends up in the set and later in a query's IN clause, where it matches nothing useful. Guard against it when collecting:
List<Contact> contacts = [SELECT Id, AccountId FROM Contact LIMIT 200];
Set<Id> accountIds = new Set<Id>();
for (Contact c : contacts) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];This is the most common use of a Set in Apex. You collect Ids from one set of records, drop the duplicates automatically, and bind the set to a second query.
Ids compare by value
A Set<Id> treats the 15-character and 18-character forms of the same record Id as one element, because Id values are compared as records, not as raw text. A Set<String> holding Id strings does not do this. If you mix both forms as strings, the same record can appear twice. Use Set<Id> whenever the values are record Ids.
sObjects compare by field values
For sObjects, equality depends on the object type and on the field values the record currently holds. Two separate Account objects with the same Id and the same field values count as equal. Two new accounts with no Id but identical fields also count as equal, so a set collapses them into one.
Account a1 = new Account(Name = 'Acme');
Account a2 = new Account(Name = 'Acme');
Set<Account> accts = new Set<Account>{a1, a2};
System.debug(accts.size()); // 1Because equality follows field values, changing a record after you add it to a set can break the set's lookups. The set filed the record under its old values. Prefer Set<Id> over Set<SObject> for membership checks. If you must keep records in a set, do not modify them while they are in it.
Ordering
Sets do not promise an order. A set of strings may print in an order that looks sorted in your test, and then print differently with other data. Never write code whose correctness depends on that order. If you need sorted output, copy the set into a list and sort it:
Set<String> tags = new Set<String>{'soql', 'apex', 'trigger'};
List<String> ordered = new List<String>(tags);
ordered.sort();
System.debug(ordered); // (apex, soql, trigger)Common errors
- Using index syntax.
tags[0]andtags.get(0)do not compile on a set. Iterate with aforloop, or convert to a list first. - Expecting case-insensitive matching.
contains('Apex')is false when the set holds'apex'. Normalize on the way in and on the way out. - Letting null in. A null in a
Set<Id>used inIN :idsadds noise to the query and hides data bugs. Filter nulls when collecting. - Storing records instead of Ids. Sets of sObjects depend on mutable field values. Use Ids.
- Relying on order. Test output that happens to look stable is not a guarantee.
- Mixing Id and String sets. If you need to compare against Ids, keep the element type
Id, and do not convert them to strings.
Why it matters for bulk code
Triggers and batch jobs receive many records at once. A Set<Id> lets you gather the distinct parent Ids from all of them, run one query, and avoid repeating the same parent in the IN clause. Later chapters combine this with maps to look up parent data without querying inside a loop.
Exercise
A trigger collects AccountId from 200 contacts into a Set<Id>. Ten contacts have no account, and many share the same account. Write the loop that builds the set so it contains no nulls, and say how many times a repeated account Id appears in the set.
Show answer
Use a null check before adding:
for (Contact c : contacts) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
A repeated account Id appears exactly once, because add ignores values already present (and returns false). The ten contacts with no account are skipped by the null check, so the set holds only distinct, non-null Ids.
Exercise
You build Set<String> names from the list {'Ada', 'ada', 'Grace', 'Ada'} using new Set<String>(list). What does names.size() return, and what one change makes 'Ada' and 'ada' count as the same element?
Show answer
It returns 3, because strings are case-sensitive: 'Ada', 'ada', and 'Grace' are distinct, and the second 'Ada' is a duplicate. To treat 'Ada' and 'ada' as one element, convert each value with toLowerCase() (after checking it is not null) before calling add, which gives a size of 2.