Sub topic 4
Sets, Maps and Lists: the bulkification toolkit
This chapter assumes you can write basic Apex, know what the List, Set and Map types are, and can read simple SOQL and DML. It also assumes you know what a trigger is. Here you will learn which collection fits which job, and how to combine them into one pattern.
Three collections, three jobs
Bulkified code does its database work once for the whole batch, not once per record. Each collection type has a specific role in that.
| Collection | Role in bulk code | Why it fits |
|---|---|---|
| `Set<Id>` | Collect the keys you need to query | Removes duplicates, so 200 Contacts of one Account give one Id |
| `Map<Id, SObject>` | Look up a record by its Id | A lookup does not run a query or scan a list |
| `List<SObject>` | Collect records to write | DML accepts a list, so one statement covers many records |
The four-step pattern
Almost every bulkified trigger follows the same steps:
- Loop over
Trigger.newand collect the Ids you need into a Set. - Run one query that filters with
IN :setand store the result in a Map. - Loop again and read related data from the Map.
- Add changed records to a List and run DML once after the loop.
Building a Map straight from a query
The Map constructor accepts a list of records and keys each one by its Id. This turns a query result into a lookup table in one line:
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);This shortcut only works for Id keys. If you need another key, such as an email address or an external Id, build the Map with a loop.
Grouping children under a parent
A single parent often has several related records. In that case the Map value is a List. The trigger below reads all Contacts of the updated Accounts with one query. It groups them by AccountId and updates them with one DML statement.
trigger AccountAfterUpdate on Account (after update) {
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Contact c : [
SELECT Id, AccountId
FROM Contact
WHERE AccountId IN :Trigger.newMap.keySet()
]) {
if (!contactsByAccount.containsKey(c.AccountId)) {
contactsByAccount.put(c.AccountId, new List<Contact>());
}
contactsByAccount.get(c.AccountId).add(c);
}
List<Contact> toUpdate = new List<Contact>();
for (Account a : Trigger.new) {
List<Contact> related = contactsByAccount.get(a.Id);
if (related == null) {
continue;
}
for (Contact c : related) {
c.Description = 'Account: ' + a.Name;
toUpdate.add(c);
}
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}The trigger uses one query and at most one DML statement, whether 1 or 200 Accounts fire it. The nested loops still cost CPU time, but they run in memory and do not consume query or DML limits.
Common errors
- A null result from
get.map.get(key)returnsnullwhen the key is missing. Reading a field on that result throws aNullPointerException. Check fornullfirst, as the examples do. - Forgetting to create the inner list. In a
Map<Id, List<Contact>>, callingget(key).add(...)before the firstputfails. UsecontainsKeyand create the list, as shown above. - Querying with a null Id. A Contact with no
AccountIdaddsnullto your Set. This does not break the query, butaccounts.get(null)returnsnull. Skip null Ids when you collect them, and check the lookup result. - Searching a List inside a loop.
list.contains(x)scans the whole list on every call. With large batches this wastes CPU time. Use a Set for membership checks. - Updating the Map's records and expecting a save. Changing a record fetched from a Map only changes it in memory. The change reaches the database only when the record is in a List passed to DML.
Quick reference
- Use a Set when you need unique values or fast membership tests.
- Use a Map when you need to find a record by key.
- Use a List when you need to keep records in order or pass them to DML.
- Use
Map<Id, List<SObject>>when a key can have many records.
Exercise
A trigger on Opportunity (before insert) needs the Industry of each Opportunity's Account, and some Opportunities have no Account. Which collections do you use, and what must you guard against?
Show answer
Collect the non-null AccountIds into a Set<Id>. Run one query with WHERE Id IN :accountIds and store the result as a Map<Id, Account>. In a second loop, call get(opp.AccountId) and check that the result is not null before reading Industry. Skipping null AccountIds when building the Set avoids pointless lookups. The null check on the Map result avoids a NullPointerException for Opportunities with no Account.