Sub topic 4
Sets, Maps and Lists: the bulkification toolkit
This chapter assumes you can write basic Apex classes and triggers, and that you know the syntax of List, Set and Map. You should also know simple SOQL and DML, and that Trigger.new holds the records of the current batch. The chapter covers which collection to use for which job, and the edge cases that cause bugs in bulk code.
Why collections are the core of bulk code
A trigger receives up to 200 records per chunk, and a transaction can contain several chunks. Per-record logic that runs a query or DML statement each time quickly uses up the limits. Bulkified code replaces that with three steps:
- Loop once over the incoming records and collect what you need into collections.
- Run one query (or a fixed small number of queries) using those collections.
- Loop again over the incoming records and use the results, then run DML once on a collection of changes.
Each collection type has a distinct role in this pattern.
| Collection | Ordered | Duplicates | Typical bulk role |
|---|---|---|---|
| `List<T>` | Yes, by index | Allowed | Holds records to insert or update. Receives query results. Is the type DML accepts. |
| `Set<T>` | No | Removed automatically | Collects unique keys, mostly Ids, to bind into `IN :set`. |
| `Map<K, V>` | No | Unique keys, values may repeat | Looks up a record or group of records by key without a nested loop. |
The next diagram shows how the pieces connect.
Sets: unique keys for a query
A Set removes duplicates for you. If 200 Contacts belong to 3 Accounts, the set holds 3 Ids. This keeps the IN list short, which helps query performance and readability.
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}Useful Set methods:
add(value)returnstrueif the value was new andfalseif it was already present.contains(value)checks membership.addAll,removeAllandretainAllcombine sets (union, difference and intersection). They also accept a list.new Set<Id>(listOfIds)builds a set from a list of Ids and removes duplicates in one step.
A Set is unordered. Do not rely on iteration order, and do not use a set where you need to keep the sequence of records.
Getting a Set of Ids from records
There is no direct constructor that turns a list of SObjects into a set of their Ids. Two common ways:
// Option 1: read the key set of Trigger.newMap (after insert, before/after update)
Set<Id> ids = Trigger.newMap.keySet();
// Option 2: build a Map from a list of records with Ids, then take its keys
List<Account> accounts = [SELECT Id FROM Account LIMIT 10];
Set<Id> accountIdSet = new Map<Id, Account>(accounts).keySet();Trigger.newMap does not exist in before insert, because the records have no Ids yet. In that event Trigger.newMap is null, so read the field values you need from Trigger.new instead.
Maps: replacing nested loops and per-record queries
A Map stores values under unique keys, and get(key) finds a value without scanning. Looking something up by key is a hash lookup. A nested loop that searches a list for every record grows with the product of the two list sizes. That cost counts against the CPU time limit.
The query-to-Map constructor
When you key by record Id, a query result converts directly into a map:
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);This constructor only works with Id as the key and the SObject as the value. It uses one query and no loop.
Keys other than Id
For any other key, such as a name or an external Id, build the map with a loop. Pay attention to case. String keys in a Map are case-sensitive, while SOQL string comparison is not. Normalize both sides:
public class AccountMatcher {
public static Map<String, Account> accountsByLowerName(Set<String> names) {
Map<String, Account> result = new Map<String, Account>();
if (names.isEmpty()) {
return result;
}
for (Account a : [SELECT Id, Name FROM Account WHERE Name IN :names]) {
result.put(a.Name.toLowerCase(), a);
}
return result;
}
}When you later call result.get(someName.toLowerCase()), a record named "ACME" and a lookup for "acme" match. Without the toLowerCase() calls the lookup would return null. If two records share a normalized key, the later put overwrites the earlier one. Decide whether that is acceptable or whether you need a Map<String, List<Account>>.
One-to-many: Map of Lists
Many real problems have several children per parent. Use a Map<Id, List<SObject>> and create each list the first time you see a key:
trigger OpportunityAfter on Opportunity (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Opportunity o : Trigger.new) {
if (o.AccountId != null) {
accountIds.add(o.AccountId);
}
}
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Contact c : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds]) {
if (!contactsByAccount.containsKey(c.AccountId)) {
contactsByAccount.put(c.AccountId, new List<Contact>());
}
contactsByAccount.get(c.AccountId).add(c);
}
List<Task> tasks = new List<Task>();
for (Opportunity o : Trigger.new) {
List<Contact> related = contactsByAccount.get(o.AccountId);
Integer count = (related == null) ? 0 : related.size();
tasks.add(new Task(
WhatId = o.Id,
Subject = 'Review account contacts',
Description = 'Contacts on the account: ' + count
));
}
if (!tasks.isEmpty()) {
insert tasks;
}
}The trigger runs one query and one DML statement whether it receives 1 or 200 Opportunities. The containsKey check matters: calling contactsByAccount.get(c.AccountId).add(c) for a new key throws a NullPointerException because get returned null.
Map behavior to remember
geton a missing key returnsnull. It does not throw. Always handle that case before you use the result.puton an existing key replaces the value and returns the old one.keySet()returns aSetandvalues()returns aList. Neither has a guaranteed order.- A Map of SObjects holds references, not copies. Changing a record you fetched with
getchanges the record inside the map too. - Do not use an SObject as a key. Its hash code depends on its field values, so changing a field after
putcan make the key unfindable.
Ids as keys: 15 and 18 characters
Salesforce Ids exist in a case-sensitive 15-character form and a case-insensitive 18-character form. When a value has the Id type, Apex works with the 18-character form, so Set<Id> and Map<Id, ...> behave correctly even if you assign a 15-character value.
The problem appears when Ids are stored as String. A Set<String> or Map<String, ...> compares text exactly, so a 15-character and an 18-character version of the same Id count as different keys. Keep Ids typed as Id for as long as possible. If you must convert, use Id.valueOf(str) or assign to an Id variable before you add to a collection.
Lists: the DML currency and ordered results
A List keeps order and allows duplicates. In bulk code it has two main uses:
- It holds the records you will pass to
insert,update,deleteorupsert. One DML statement on a list counts as one DML statement, no matter how many records it contains. The records still count against the DML rows limit. - It receives query results when you assign
[SELECT ...]to a list variable.
Edge cases in list handling:
list[0]throws aListExceptionon an empty list. CheckisEmpty()orsize()first.- Assigning a query to a single SObject, as in
Account a = [SELECT Id FROM Account WHERE Name = 'X'];, throwsQueryExceptionwhen the query returns zero or more than one row. Assign to a list when the number of rows is not certain. - Skip the DML call on an empty list. DML on an empty list does not fail, but the
isEmpty()guard makes the intent clear. - A list can hold the same record twice, and an
updateon a list with duplicate Ids throws aDmlException. When one record may be added more than once, collect changes in aMap<Id, SObject>and callupdate map.values().
Map<Id, Account> toUpdate = new Map<Id, Account>();
for (Contact c : contacts) {
// Two contacts of the same account write to one entry, not two
toUpdate.put(c.AccountId, new Account(Id = c.AccountId, Description = 'Has contacts'));
}
if (!toUpdate.isEmpty()) {
update toUpdate.values();
}Collections and the other limits
Collections remove query and DML problems, but they use memory. Everything you store counts toward the heap size limit, so avoid loading wide result sets or every field when you need two. A query that returns more than 50,000 rows still fails, however you store the rows. Limits on rows and heap are covered in other chapters. For now, query only the fields you need and filter with the IN set so the map holds only relevant records.
Common mistakes
- Querying inside the second loop because the map lacked a key. Build the map completely before the second loop starts.
- Forgetting that a parent may have no children, so
getreturnsnull. - Building the set from
Trigger.oldfor an insert.Trigger.oldis not available on insert, so useTrigger.new. - Mixing key types, for example putting
Idkeys in and callinggetwith aString. - Passing an empty set to
IN. The query is valid and returns no rows, but it still costs a query. Return early when the set is empty if the query is not needed.
Exercise
A before insert trigger on Contact must set c.Title = 'Primary' on any Contact whose Account has no other Contacts yet. You have Trigger.new (up to 200 Contacts). Describe the collections you would use, how many queries and DML statements the trigger needs, and one case you must handle so the code does not fail with a null reference.
Show answer
Loop over Trigger.new and add each non-null AccountId to a Set<Id>. Run one query that selects AccountId from Contact where AccountId IN :accountIds, and store the results in a Map<Id, List<Contact>> (or a Set<Id> of Account Ids that already have Contacts). Loop over Trigger.new again and set the Title when the map has no entry for c.AccountId. The trigger needs one query and no DML, because in a before trigger changes to Trigger.new are saved automatically. Handle Contacts with a null AccountId (skip them) and parents with no entry in the map, because Map.get returns null for a missing key. You must also account for several new Contacts in the same batch that share an Account, for example by tracking Account Ids already assigned in a Set<Id> during the second loop.