Sub topic 5
Working with Set methods
A Set holds unique values with no guaranteed order. This chapter covers the methods you use to fill, query, and combine Sets. It assumes you can already declare a Set and know why you would pick one over a List. It also assumes you are comfortable with Apex loops and basic SOQL.
The core methods
Most Set work uses a small group of methods.
| Method | Returns | What it does |
|---|---|---|
| `add(e)` | `Boolean` | Adds `e`. Returns `true` if the Set changed, `false` if `e` was already there. |
| `addAll(c)` | `Boolean` | Adds every element of a List or Set. Returns `true` if the Set changed. |
| `contains(e)` | `Boolean` | Tests membership. |
| `containsAll(c)` | `Boolean` | `true` if every element of the List or Set is present. |
| `remove(e)` | `Boolean` | Removes `e`. Returns `true` if it was present. |
| `removeAll(c)` | `Boolean` | Removes every element found in the List or Set. |
| `retainAll(c)` | `Boolean` | Keeps only elements that also appear in the List or Set. |
| `size()` | `Integer` | Number of elements. |
| `isEmpty()` | `Boolean` | `true` when the size is 0. |
| `clear()` | `void` | Removes all elements. |
| `clone()` | `Set<T>` | Returns a shallow copy. |
Methods that return Boolean tell you whether the Set changed. This is useful when you need to know if a value is new.
Set<String> seen = new Set<String>();
List<String> incoming = new List<String>{'A-1', 'B-2', 'A-1', 'C-3'};
for (String code : incoming) {
if (seen.add(code)) {
System.debug('First time: ' + code);
} else {
System.debug('Duplicate: ' + code);
}
}
System.debug(seen.size()); // 3You do not need to call contains before add. add already ignores duplicates and reports the result.
Removing duplicates from a List
Pass a List to the Set constructor to drop duplicates. If you need a List again, pass the Set to the List constructor.
List<String> raw = new List<String>{'x', 'y', 'x', 'z', 'y'};
Set<String> unique = new Set<String>(raw);
List<String> deduped = new List<String>(unique);
System.debug(deduped.size()); // 3The order of deduped is not guaranteed to match raw. If order matters, keep a List and use a Set only as a lookup of values already seen.
List<String> raw = new List<String>{'x', 'y', 'x', 'z', 'y'};
Set<String> seen = new Set<String>();
List<String> ordered = new List<String>();
for (String s : raw) {
if (seen.add(s)) {
ordered.add(s);
}
}
System.debug(ordered); // (x, y, z)Set algebra
Three methods give you the standard set operations. All three modify the Set they are called on. To keep the original, call clone() first.
| Operation | Method | Result |
|---|---|---|
| Union | `addAll` | Elements in either Set. |
| Intersection | `retainAll` | Elements in both Sets. |
| Difference | `removeAll` | Elements in the first Set but not the second. |
Set<String> a = new Set<String>{'apex', 'soql', 'trigger'};
Set<String> b = new Set<String>{'soql', 'flow'};
Set<String> union = a.clone();
union.addAll(b); // apex, soql, trigger, flow
Set<String> intersection = a.clone();
intersection.retainAll(b); // soql
Set<String> difference = a.clone();
difference.removeAll(b); // apex, trigger
System.debug(union.size()); // 4
System.debug(intersection); // {soql}
System.debug(difference.size()); // 2
System.debug(a.containsAll(intersection)); // true
System.debug(a.size()); // 3, a is unchangedA practical use of difference is finding what is missing. Suppose you need a record for every code in a list and want to know which codes have none yet.
Set<String> wanted = new Set<String>{'US', 'CA', 'MX'};
Set<String> existing = new Set<String>{'US'};
Set<String> missing = wanted.clone();
missing.removeAll(existing);
System.debug(missing); // {CA, MX} in some orderCollecting Ids from records
The most common Set in real Apex code is a Set<Id>. You gather Ids from a record list and pass them to a SOQL IN clause.
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
];
System.debug(accounts.size() <= accountIds.size()); // trueContacts from the same account would produce repeated Ids in a List. The Set keeps each Id once, so the bind variable stays small.
Edge cases
Null is a valid element
A Set can hold null once. Unlike a Map key lookup, nothing throws. This often surprises people when a field is blank.
Set<String> values = new Set<String>{'a', null, 'b', null};
System.debug(values.size()); // 3
System.debug(values.contains(null)); // true
values.remove(null);
System.debug(values.size()); // 2Either check for null before add, or call remove(null) before you use the Set in a query.
Strings are case-sensitive
'Ada' and 'ada' are different elements. To compare case-insensitively, normalize the values as you add them.
Set<String> emails = new Set<String>();
List<String> input = new List<String>{'[email protected]', '[email protected]'};
for (String e : input) {
if (e != null) {
emails.add(e.toLowerCase());
}
}
System.debug(emails.size()); // 1Normalize the value you pass to contains in the same way, or the lookup will miss.
Order is not guaranteed
Do not rely on the order of System.debug output or loop order. Two Sets with the same elements are equal regardless of order, so equals compares contents.
Set<Integer> s1 = new Set<Integer>{1, 2, 3};
Set<Integer> s2 = new Set<Integer>{3, 2, 1};
System.debug(s1.equals(s2)); // trueIteration and modification
You can loop over a Set with for (T item : mySet). Do not add to or remove from the Set inside that loop. Collect the changes in a second Set or List and apply them after the loop.
Set<Integer> numbers = new Set<Integer>{1, 2, 3, 4, 5, 6};
Set<Integer> evens = new Set<Integer>();
for (Integer n : numbers) {
if (Math.mod(n, 2) == 0) {
evens.add(n);
}
}
numbers.removeAll(evens);
System.debug(numbers.size()); // 3SObjects in a Set
A Set of SObjects compares records by their field values, not by reference. Two Accounts with the same Id and field values count as one. This has a trap. If you change a field on a record after adding it to a Set, the Set can no longer find it reliably, and contains may return false. For this reason, prefer a Set<Id> and keep the records in a List or Map.
clone is shallow
clone() copies the Set, not the objects inside it. For Sets of Strings, Ids, or Integers this does not matter. For a Set of SObjects, the copy and the original point to the same records.
Common errors
- Expecting order. Sorting a Set is not possible. Copy it to a List and call
sort(). - Forgetting the copy. Using
retainAllon the Set you still need, then wondering why it shrank. - Passing a Set with
nullto a query. AnullId in anINclause matches no real record and hides data problems. - Mixed case strings. Duplicates that differ only by case both stay in the Set.
- Mutating records held in a Set. Changing fields on an SObject after adding it breaks lookups.
Exercise
You have Set<String> a = new Set<String>{'x', 'y', 'z'}; and Set<String> b = new Set<String>{'y', 'z', 'w'};. Write code that produces a new Set holding the elements that are in a or b but not in both, without changing a or b. What does it contain?
Show answer
Build the union and the intersection from clones, then remove the intersection from the union.
Set<String> both = a.clone();
both.retainAll(b); // y, z
Set<String> either = a.clone();
either.addAll(b); // x, y, z, w
either.removeAll(both); // x, w
The result contains 'x' and 'w'. The Sets a and b are unchanged because only clones were modified.
Exercise
What does this code print, and why? Set<String> s = new Set<String>{'a'}; System.debug(s.add('a')); System.debug(s.add('A')); System.debug(s.size());
Show answer
It prints false, true, and 2. The first add returns false because 'a' is already present. The second returns true because Set<String> is case-sensitive, so 'A' is a new element. The Set then holds two elements.