Sub topic 12
Grouping records with a Map of Lists
This chapter assumes you know basic Apex syntax, how to read Account and Contact records, and simple SOQL queries. You should also know how List and Map work. Here you combine them to group records by a key.
Why group records
Often you query child records, such as Contacts, and then need to process them per parent, such as per Account. A Map of Lists solves this. The key is the parent Id. The value is a List of the child records that belong to that parent.
Once the data is grouped, you can look up all Contacts for any Account with one get call. You never need a nested loop or a query inside a loop.
The pattern
The type is Map<Id, List<Contact>>. The loop follows three steps for each record:
- Read the grouping key from the record.
- If the map has no entry for that key, put a new empty List there.
- Get the List and add the record to it.
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Contact c : contacts) {
if (!contactsByAccount.containsKey(c.AccountId)) {
contactsByAccount.put(c.AccountId, new List<Contact>());
}
contactsByAccount.get(c.AccountId).add(c);
}Step 2 matters. get returns null for a missing key. Calling add on null throws a System.NullPointerException. The containsKey check creates each List the first time its key appears.
How the data flows
Using the grouped data
After grouping, read the Lists by key. This example queries Accounts and Contacts once each, then reports a count per Account.
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 10]
);
List<Contact> contacts = [
SELECT Id, LastName, AccountId
FROM Contact
WHERE AccountId IN :accountsById.keySet()
];
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Contact c : contacts) {
if (!contactsByAccount.containsKey(c.AccountId)) {
contactsByAccount.put(c.AccountId, new List<Contact>());
}
contactsByAccount.get(c.AccountId).add(c);
}
for (Account a : accountsById.values()) {
List<Contact> related = contactsByAccount.get(a.Id);
Integer total = related == null ? 0 : related.size();
System.debug(a.Name + ': ' + total + ' contacts');
}Accounts with no Contacts never get a key, so get returns null for them. The final loop checks for null before calling size.
Common errors
- Skipping the
containsKeycheck. The first record for each key throws aNullPointerException. - Forgetting that a missing key returns null. When you read the map later, handle accounts that have no entry.
- Grouping by a null key. A Contact with no Account has a null
AccountId. The map accepts a null key, so those Contacts collect under it. Filter them out in your query or skip them in the loop if you don't want that. - Querying inside the loop. Run the query once, group the results, then look up by key. This keeps you within governor limits.
Exercise
Exercise
A trigger needs to process all Opportunities for each Account in Trigger.new. Why is it better to build a Map<Id, List<Opportunity>> from one query than to query Opportunities inside the loop over Accounts? What must you check when you read from the map?
Show answer
A query inside the loop runs once per Account, so a batch of more than 100 Accounts exceeds the limit of 100 SOQL queries per transaction. One query before the loop, followed by grouping into a Map<Id, List<Opportunity>>, uses a single query for any batch size. When you read from the map, check for null (or use containsKey), because an Account with no Opportunities has no key and get returns null.