Sub topic 1
Why Apex has three collection types and how to choose
Prerequisites
This chapter assumes you know basic Apex syntax: variables, primitive types, loops, and conditionals. It also assumes you know what SObjects such as Account and Contact are, and that you can read a basic SOQL SELECT query.
Three collections, three questions
Apex gives you three built-in collection types. Each one answers a different question about your data.
- A List answers "in what order, and at which position?" It keeps elements in insertion order, reads them by zero-based index, and allows duplicates.
- A Set answers "is this value present, and is it unique?" It stores each value at most once and does not guarantee order.
- A Map answers "what value belongs to this key?" It stores key-value pairs, and each key appears once.
Most Apex code on the platform is built from these three. Triggers and batch jobs receive records as collections, and SOQL returns them as collections. Choosing the right type early keeps your code short and avoids repeated loops.
Comparing the types
| Feature | List | Set | Map |
|---|---|---|---|
| Order | Insertion order, indexed | No guaranteed order | No guaranteed order |
| Duplicates | Allowed | Ignored | Keys unique, values may repeat |
| Access by | Index | Value (`contains`) | Key (`get`) |
| Typical use | Records to insert or update | Unique Ids for a query filter | Fast lookup of a record by Id |
The three types in action
The same small task shows the differences. Here a List holds names by position.
List<String> names = new List<String>{'Ada', 'Grace'};
names.add('Linus');
names.add(0, 'Alan');
System.debug(names.get(1)); // Ada
System.debug(names[2]); // Grace
names.sort();
System.debug(names); // (Ada, Alan, Grace, Linus)A Set ignores a repeated value. Its add method returns false when the element was already present.
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')); // trueA Map stores one value per key. Calling get with a missing key returns null, so the code below checks for null before incrementing.
List<String> words = new List<String>{'a', 'b', 'a'};
Map<String, Integer> counts = new Map<String, Integer>();
for (String w : words) {
Integer current = counts.get(w);
counts.put(w, current == null ? 1 : current + 1);
}
System.debug(counts.get('a')); // 2
System.debug(counts.get('z')); // nullHow to choose
Ask these questions in order:
- Do you need to find a value quickly from some other value, such as an Account by its Id? Use a Map.
- Does position or order matter, or do you need to insert or update records, which takes a List? Use a List.
- Do you only need to know which distinct values exist, or whether one is present? Use a Set.
Combinations are common. A frequent pattern is to collect Ids in a Set, query with them, and store the results in a Map. Later chapters build on this.
Common mistakes
- Relying on Set or Map ordering. Apex does not promise any order for either, so do not write code that depends on it.
- Using a List to check membership.
list.contains(x)scans the list, while a Set is built for this question. - Reading a Map key without a
nullcheck. A missing key returnsnull, and using that result can throw aNullPointerException.
Exercise
You receive 200 Contact records and need to find, for any AccountId, the matching Account quickly, without looping through all accounts each time. Which collection type should hold the Accounts, and what should the key be?
Show answer
Use a Map, with the Account Id as the key and the Account record as the value (Map<Id, Account>). Lookups by key with get then avoid a loop over the whole list.
Exercise
You add the string 'apex' to a Set<String> that already contains 'apex'. What does add return, and what happens to the size of the Set?
Show answer
add returns false, and the size stays the same, because a Set stores each value at most once.