Sub topic 7
Collecting IDs and values with Sets, Lists, and Maps
This chapter assumes you know basic Apex syntax, sObjects, and SOQL and DML statements. It also assumes you know that a trigger receives up to 200 records per invocation. Here you will learn the three collection types that make bulk processing possible.
Why collections matter in triggers
Once SOQL and DML are out of loops, the loop has a different job: it gathers data. A later step uses that data in a single query or a single DML statement. Apex gives you three collection types for this.
| Collection | Holds | Duplicates | Typical trigger use |
|---|---|---|---|
| `Set<T>` | Unique values, unordered | Ignored | Collecting IDs for a `WHERE ... IN` clause |
| `List<T>` | Ordered values | Allowed | Collecting records to insert or update |
| `Map<K, V>` | Key-value pairs | Keys are unique | Looking up a related record by ID |
Set: collect unique IDs
If 200 contacts belong to five accounts, you only need to query five accounts. A Set removes duplicates for you, so the query stays small.
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}Check for null before adding. A null ID in the set is legal, but it adds nothing useful to the query.
List: collect records to write
A List gathers the records you want to save. You build it inside the loop and run DML once after the loop ends.
List<Task> tasks = new List<Task>();
for (Opportunity opp : Trigger.new) {
if (opp.StageName == 'Closed Won') {
tasks.add(new Task(Subject = 'Follow up', WhatId = opp.Id));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}The isEmpty() check avoids a pointless DML statement. An empty insert does not throw an error, but it is still counted as a DML statement against the limit.
Map: look up results by key
A Map replaces a query inside a loop. You can build one directly from a SOQL result, and Apex uses each record's ID as the key.
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account a = accountsById.get(c.AccountId);
if (a != null && a.Industry == 'Banking') {
c.Description = 'Banking contact';
}
}get() returns null when the key is missing. That happens for contacts with no account, so always check the result before reading a field.
The standard pattern
Most bulkified triggers follow the same three passes.
Common mistakes
- Using a
List<Id>where aSet<Id>fits. The query still works, but duplicate IDs make the collection larger than it needs to be. - Calling
accountsById.get(c.AccountId)and reading a field without a null check. This throws aNullPointerExceptionfor any record with no match. - Building a
Mapfrom a query that returns many fields you never use. Select only the fields the trigger needs.
Exercise
A trigger on Case needs the Contact record for each case's ContactId. Which collection do you use to gather the IDs, and which do you use to look up each contact afterward?
Show answer
Use a Set<Id> to gather the unique ContactId values, because it removes duplicates. After one SOQL query with WHERE Id IN :contactIds, store the results in a Map<Id, Contact> and call get() with each case's ContactId, checking for null.
Exercise
Why check !tasks.isEmpty() before running insert tasks?
Show answer
An empty insert does nothing useful but still counts as a DML statement against the governor limit. The check skips it when no records were added.