Sub topic 7
Collecting IDs and values with Sets, Lists, and Maps
This chapter assumes you know basic Apex syntax, SOQL and DML. It also assumes you know that a trigger receives a list of records in Trigger.new. Once SOQL and DML are out of your loops, collections carry the data between the steps of a bulkified trigger. This chapter covers what each collection type guarantees and which one to pick for which job. It also covers the mistakes that cause bugs in triggers.
The three collection types
Apex has three collection types, and bulk code usually combines them.
| Type | Order | Duplicates | Typical trigger use |
|---|---|---|---|
| `List<T>` | Keeps insertion order | Allowed | Records to insert or update, ordered results |
| `Set<T>` | No guaranteed order | Removed automatically | Distinct IDs or values to filter a query |
| `Map<K, V>` | Unordered by key | One value per key; a repeated `put` overwrites | Fast lookup of a record or a group of records by key |
A common flow has four steps. A first loop gathers keys into a Set. One query then fetches the related data. The results go into a Map, and a second loop looks values up in that Map.
Sets: distinct keys
A Set removes duplicates for you. If 200 contacts belong to 3 accounts, the Set of account IDs has 3 entries. A query that filters with IN :accountIds then stays small.
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}The null check matters. A Set accepts null as a value, so without the check it can hold a null entry. In a WHERE ... IN :accountIds clause, that entry produces no useful match and just adds noise. Skip nulls when you collect.
You can also get a Set of IDs without a loop in some contexts:
Set<Id> ids = Trigger.newMap.keySet();Trigger.newMap is only populated where records already have IDs. That means after insert, before update, after update, and after undelete. In before insert it is null, so calling keySet() there throws a NullPointerException. Records in before insert have no IDs yet.
Sets of values other than IDs
Sets work for any primitive value. This example collects email addresses so a query can look for existing duplicates.
Set<String> emails = new Set<String>();
for (Contact c : Trigger.new) {
if (String.isNotBlank(c.Email)) {
emails.add(c.Email.toLowerCase());
}
}Set<String> is case-sensitive, so [email protected] and [email protected] count as two entries. Normalize with toLowerCase() before adding, and normalize again when you look values up.
Lists: ordered records to save
A List holds the records you will pass to one DML statement. Create an empty List before the loop, add to it inside the loop, and run DML once after the loop.
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 is optional, because DML on an empty list is a no-op that does not count a DML row. It does make the intent clear. The next chapters cover DML in detail.
Lists keep order, which gives two useful properties. Results of insert tasks line up by index with the list you passed in. A Database.SaveResult[] also follows that index order.
Maps: lookups by key
A Map answers the question "given this key, what is the value?" in a single call. In a trigger, the keys are almost always IDs.
The shortest way to build a Map keyed by ID is to pass a query result to the constructor.
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);The constructor reads each record's Id and uses it as the key. The next chapter covers the query side in detail. This chapter covers the Map operations you use afterward.
| Method | What it does |
|---|---|
| `get(key)` | Returns the value, or `null` if the key is missing |
| `containsKey(key)` | Returns `true` if the key exists |
| `put(key, value)` | Adds or overwrites an entry |
| `keySet()` | Returns the keys as a Set |
| `values()` | Returns the values as a List |
| `remove(key)` | Deletes an entry and returns the old value |
get returns null for a missing key, and also when you pass null as the key. That is why the lookup loop in the previous example is safe for contacts with no account, as long as the code then checks the result for null before using it.
Grouping: one key, many values
A Map holds one value per key. To keep several records per key, make the value a List. This pattern is the most common one in trigger code that works with parent and child records.
public with sharing class ContactGrouper {
public static Map<Id, List<Contact>> groupByAccount(List<Contact> contacts) {
Map<Id, List<Contact>> contactsByAccountId = new Map<Id, List<Contact>>();
for (Contact c : contacts) {
if (c.AccountId == null) {
continue;
}
if (!contactsByAccountId.containsKey(c.AccountId)) {
contactsByAccountId.put(c.AccountId, new List<Contact>());
}
contactsByAccountId.get(c.AccountId).add(c);
}
return contactsByAccountId;
}
}The loop creates the inner List the first time it sees an account, then adds to it. get returns a reference to the stored List, not a copy, so add changes the List inside the Map. You do not need to call put again.
Without the containsKey check, get returns null for a new account and add throws a NullPointerException. This is one of the most frequent bugs in first-time bulk code.
Counting and summing
Use a Map with a numeric value to count or total per key.
Map<Id, Integer> contactCountByAccount = new Map<Id, Integer>();
for (Contact c : Trigger.new) {
if (c.AccountId == null) {
continue;
}
Integer current = contactCountByAccount.get(c.AccountId);
contactCountByAccount.put(c.AccountId, current == null ? 1 : current + 1);
}Here the missing-key null from get is useful. It tells you this is the first record for that account.
Choosing the key type
Use the Id type for keys that are record IDs, not String. Apex treats an Id value as an 18-character identifier, so a 15-character and an 18-character form of the same ID match as the same key. As Strings they would be two different keys. If you must build a String-keyed Map, convert with String.valueOf(id) consistently on both sides.
For other values, pick a key that is unique in your data. A Map keyed by Name silently overwrites accounts that share a name, because put replaces the old value without any error. If duplicates are possible, group into Map<String, List<Account>>, or use the ID as the key.
Common mistakes
- Using a List where a Set fits. A List of 200 IDs with many repeats makes the query filter larger and calls
containsin a slow linear scan. Use a Set for membership tests. - Adding
nullto the Set. Guard with a null check beforeadd. - Calling
getand using the result directly. A missing key returnsnull. Check it before you read fields. - Reading
Trigger.newMapinbefore insert. It isnullthere. - Rebuilding a Map inside the loop. The Map should be built once, before the loop that uses it.
Exercise
A before update trigger on Contact must find, for each distinct Account, how many of the updated contacts are in the batch, and skip contacts with no account. Which collection types do you use, what is the key, and what happens if you call get on a key that was never added?
Show answer
Use a Map<Id, Integer> keyed by AccountId. In the loop, skip contacts where AccountId == null, read the current count with get, and put back current == null ? 1 : current + 1. If you call get on a key that was never added, it returns null and does not throw an error, so the null check is how you detect the first record for that account. If you also need the contacts themselves, use Map<Id, List<Contact>> and create the inner List with containsKey before adding to it.
Exercise
A trigger builds Set<Account> from Trigger.new records and later changes Industry on one of them. Why can the Set stop working correctly, and what should you store instead?
Show answer
sObject equality depends on field values, so changing a field after adding the record changes how it compares. The Set may no longer find that record. Store the record Id in a Set<Id>, or keep the records in a Map<Id, Account> keyed by Id.