Sub topic 1
Why Apex has three collection types and how to choose
Almost every Apex trigger, batch job, and controller handles many records at once. Apex gives you three collection types for this: List, Set, and Map. Each one answers a different question about your data. This chapter explains what each type guarantees, how the three differ, and how to pick one. Later chapters cover the methods of each type in detail.
Prerequisites
This chapter assumes you already know:
- Basic Apex syntax: variables, primitive types, loops, and conditionals.
- What SObjects and records are, such as Account and Contact.
- How to read a basic SOQL SELECT query.
You can run all the examples in Anonymous Apex in the Developer Console or in VS Code with the Salesforce extensions.
Why Apex has three types
A single collection type could not serve all the common jobs well. Consider three questions you ask about data in Apex:
- What is at position 3, and in what order did things arrive?
- Have I already seen this value?
- Given this key, what is the matching record?
A List answers the first, a Set the second, and a Map the third. Each type gives up some flexibility to make its own question fast and unambiguous. The guarantees below are what you are choosing between.
| Type | Order | Duplicates | Access by | Typical question |
|---|---|---|---|---|
| List | Kept in insertion order, unless you sort it | Allowed | Zero-based index | What is at position n? |
| Set | No guaranteed order | Not allowed | Membership test | Is this value present? |
| Map | No guaranteed key order | Keys are unique, values can repeat | Key | What belongs to this key? |
All three are generic. You declare the element type in angle brackets, such as List<String>, Set<Id>, or Map<Id, Account>. The compiler then rejects code that puts the wrong type in.
List: order and position
A List is an ordered sequence. Elements keep the position you gave them, you can read them by zero-based index, and the same value can appear many times.
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)Choose a List when:
- Order matters, for example a ranked result or a sorted display.
- Duplicates are meaningful.
- You need to pass records to DML.
insert,update, anddeletetake aList<SObject>, and SOQL queries return one.
Reading an index that does not exist throws a ListException. Check size() first if the list might be short.
Set: uniqueness
A Set holds each value at most once. Adding a value that is already present changes nothing, and add returns false to tell you so.
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')); // trueChoose a Set when:
- You need to remove duplicates.
- You need a quick "have I seen this?" check.
- You are collecting Ids to use in a SOQL
INclause.
A Set has no index and no guaranteed iteration order. Do not write code that depends on the order you get elements back.
String comparison in a Set is case-sensitive, so 'Apex' and 'apex' count as two values. If case should not matter, normalize with toLowerCase() before adding.
Map: lookup by key
A Map stores key-value pairs. Each key appears once and points to one value. Different keys can point to equal values.
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')); // nullChoose a Map when you repeatedly need "find the thing that goes with this key". A Map often replaces a nested loop. Without one, you loop over a second list for every item of the first. With one, you build the Map once and call get.
Two behaviors cause bugs:
getreturnsnullfor a missing key. It does not throw, so a later call on the result can fail with aNullPointerException. UsecontainsKeywhen a missing key is a real possibility.puton an existing key replaces the old value without any warning.
Map keys are case-sensitive for Strings, with the same consequence as for Sets.
How the three work together
The types are rarely used alone. A common pattern uses all three in a few lines: collect Ids into a Set, query once, turn the results into a Map, and look records up by key.
List<Contact> contacts = [
SELECT Id, LastName, AccountId
FROM Contact
WHERE AccountId != null
LIMIT 200
];
Set<Id> accountIds = new Set<Id>();
for (Contact c : contacts) {
accountIds.add(c.AccountId);
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);
for (Contact c : contacts) {
Account parent = accountsById.get(c.AccountId);
System.debug(c.LastName + ' works at ' + parent.Name);
}Each type does the job it suits:
- The List holds the contacts in the order the query returned them.
- The Set removes duplicate account Ids. Many contacts can share one account, and the query only needs each Id once.
- The Map lets you find an account from a contact in a single call, with no inner loop.
The Map constructor accepts a list of SObjects and keys each record by its Id. The code uses it here. Two queries cover any number of contacts, which is what keeps this pattern within governor limits. Chapter 13 returns to that point.
Conversions between types
You can convert between the types when the shape you have is not the shape you need:
List<String> raw = new List<String>{'x', 'y', 'x', 'z'};
Set<String> unique = new Set<String>(raw); // removes duplicates
List<String> backToList = new List<String>(unique); // order not guaranteed
System.debug(unique.size()); // 3Converting a List to a Set and back is a short way to deduplicate. The order of the result is not the original order. If you need first-seen order, loop over the original list and keep a Set of values you have already added.
A SOQL bind variable accepts either a List or a Set, so you do not have to convert before using IN :variable.
Choosing: a decision guide
Start from what you need to do with the data, not from what you have.
The same logic as questions to ask:
- If you will fetch items by something other than position, use a Map. Examples are an Id, an external key, or a name.
- If you only care whether a value is present, or you must discard repeats, use a Set.
- Otherwise, or whenever order, indexing, or DML input matters, use a List.
Some situations call for a choice that is less obvious:
- You need the order and also want to avoid duplicates. Use a List for the order and a Set alongside it to track what you have added.
- You need several values per key. Use a Map whose values are Lists, covered in the grouping chapter.
- You need a stable key from a record. Prefer
Idor a String field. Avoid using whole SObjects as Set elements or Map keys, because SObject equality depends on field values, which can change.
Common mistakes
- Relying on Set or Map ordering. The order is not guaranteed, and tests that pass today may fail later.
- Calling
geton a Map and using the result without a null check. - Using a List with
containsinside a loop. This is a linear scan on every call. A Set makes the same check fast. - Forgetting that String keys and Set values are case-sensitive.
- Declaring a collection without initializing it.
Map<Id, Account> m;isnull, and callingm.put(...)throws aNullPointerException. Usenewfirst.
Exercise
A trigger receives a list of Contacts. You need (1) the distinct AccountIds of those contacts, and (2) a way to get an Account's Name from its Id after one query. Which collection type fits each need, and why?
Show answer
Use a Set<Id> for the distinct AccountIds, because a Set discards duplicates and can be bound directly into a SOQL IN clause. Use a Map<Id, Account> for the lookup, built from the query result with the Map constructor, because get(accountId) returns the matching Account without looping.
Exercise
This code throws an error for some inputs. What is the bug, and how do you fix it? Map<String, Integer> stock = new Map<String, Integer>{'bolt' => 5}; Integer n = stock.get('nut') + 1;
Show answer
stock.get('nut') returns null because the key is missing, and adding 1 to null throws a NullPointerException. Check stock.containsKey('nut') first, or read the value into an Integer variable and treat null as 0 before adding.