Sub topic 4
Sets: unique values
This chapter assumes you know basic Apex syntax, have used Lists, and can read a simple SOQL query. A Set is a collection of unique elements with no guaranteed order. Use one when you care about "is this value present?" and not "what is at position 3?".
How a Set behaves
A Set holds each value at most once. Adding a value that is already present changes nothing. A Set has no index, so you cannot write tags[0] or call get(0). Do not rely on iteration order, because Apex does not promise one.
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')); // trueThe add method returns a Boolean. It is true if the Set changed and false if the element was already there. The Set starts with two values, the duplicate add leaves it unchanged, and the new value brings the size to 3.
Creating a Set
You can create a Set in three common ways:
- Empty:
Set<Integer> ids = new Set<Integer>(); - With a literal:
new Set<String>{'a', 'b'} - From another collection:
new Set<String>(myList)
The last form is the usual way to remove duplicates from a List.
List<String> raw = new List<String>{'a', 'b', 'a', 'c', 'b'};
Set<String> unique = new Set<String>(raw);
System.debug(unique.size()); // 3Common methods
| Method | What it does |
|---|---|
| `add(e)` | Adds `e`. Returns `false` if already present. |
| `addAll(collection)` | Adds every element of a List or Set. |
| `contains(e)` | Returns `true` if `e` is in the Set. |
| `remove(e)` | Removes `e`. Returns `true` if it was present. |
| `size()` | Returns the number of elements. |
| `isEmpty()` | Returns `true` if the Set has no elements. |
The Set method list continues in the next chapter, along with set algebra such as retainAll and removeAll.
Case sensitivity and Set types
For Strings, contains and add compare case-sensitively. 'Apex' and 'apex' count as two different values. If you want case-insensitive uniqueness, convert each value first, for example with toLowerCase(), before adding it.
Set<String> names = new Set<String>();
names.add('Apex');
names.add('apex');
System.debug(names.size()); // 2
Set<String> normalized = new Set<String>();
for (String n : names) {
normalized.add(n.toLowerCase());
}
System.debug(normalized.size()); // 1Common errors
- Trying to index a Set.
tags[0]does not compile. Convert to a List first if you need positions. - Assuming
addthrows on a duplicate. It returnsfalseand continues. - Expecting
'Apex'to match'apex'. - Using a Set when duplicates matter. If you need to count occurrences, use a Map or a List.
When to choose a Set
Choose a Set when you need fast membership checks, when you must remove duplicates, or when you need a unique collection of Ids for a SOQL IN clause. Later chapters build on this when you query with Set<Id> bind variables.
Exercise
A List named emails contains '[email protected]', '[email protected]', and '[email protected]'. Write code that produces a Set with the unique values, and say what size() returns.
Show answer
Use Set<String> unique = new Set<String>(emails);. The size is 2, because the duplicate '[email protected]' is stored only once.
Exercise
What does tags.add('apex') return when tags already contains 'apex', and does the Set change?
Show answer
It returns false, and the Set does not change.