Sub topic 12
Grouping records with a Map of Lists
This chapter assumes you can write Apex loops and conditionals. It also assumes you know the basic List and Map methods and can run a SOQL query that returns Contact or Account records. You will build the grouping pattern step by step, then look at its edge cases.
The problem: a flat list with a parent key
A SOQL query returns a flat List<SObject>. If you query 200 contacts, you get 200 records in one list, even though they belong to different accounts. Code often needs the opposite shape: "give me all contacts for this account."
You could answer that by looping over the whole list once per account. That costs work proportional to accounts times contacts. It is also easy to get wrong when the loops end up nested.
A Map<Id, List<Contact>> fixes this. The key is the parent Id, and the value is the list of child records that share that parent. You build the map in one pass over the records, then read any group with a single get call.
The basic pattern
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);
}Each iteration does three things:
- It checks whether the key already has a list.
- If not, it creates an empty list and stores it under that key.
- It fetches the list and adds the record.
Why `get(...).add(...)` changes the map
get does not return a copy of the list. It returns a reference to the same list object stored in the map. When you call add on that reference, you modify the list the map holds. You never need to call put again after the first insertion.
The same rule explains a common mistake. If you build the list in a local variable and never put it into the map, the map stays empty, because you changed an object nothing points to.
A single-lookup version
The version above calls containsKey, get, and sometimes put. You can reduce this to one get and store the result in a variable:
public class ContactGrouper {
public static Map<Id, List<Contact>> byAccount(List<Contact> contacts) {
Map<Id, List<Contact>> result = new Map<Id, List<Contact>>();
for (Contact c : contacts) {
if (c.AccountId == null) {
continue;
}
List<Contact> bucket = result.get(c.AccountId);
if (bucket == null) {
bucket = new List<Contact>();
result.put(c.AccountId, bucket);
}
bucket.add(c);
}
return result;
}
}This works because get returns null for a missing key. The name bucket is a local variable that points at the list in the map. Adding to bucket therefore adds to the map's list.
Putting the pattern in a static method gives you one tested place for the logic. Callers read ContactGrouper.byAccount(contacts) and do not repeat the loop.
Using the grouped result
Here is a complete script. It queries accounts once, queries their contacts once, groups the contacts, and reports a count per account. You can run it as anonymous Apex after saving the class above.
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 10]
);
List<Contact> contacts = [
SELECT Id, LastName, AccountId
FROM Contact
WHERE AccountId IN :accounts.keySet()
];
Map<Id, List<Contact>> grouped = ContactGrouper.byAccount(contacts);
for (Account a : accounts.values()) {
List<Contact> children = grouped.containsKey(a.Id)
? grouped.get(a.Id)
: new List<Contact>();
System.debug(a.Name + ': ' + children.size());
}Two details matter here.
accounts.keySet()supplies aSet<Id>for theINbind variable, as covered in the SOQL chapter.- An account with no contacts has no entry in
grouped. Callinggrouped.get(a.Id)returnsnull, andnull.size()throws aNullPointerException. The ternary expression substitutes an empty list, so the loop body can treat every account the same way.
Grouping by something other than an Id
The key can be any type that makes sense for the grouping. To group accounts by industry, use a String key:
Map<String, List<Account>> accountsByIndustry = new Map<String, List<Account>>();
for (Account a : [SELECT Id, Name, Industry FROM Account LIMIT 200]) {
List<Account> bucket = accountsByIndustry.get(a.Industry);
if (bucket == null) {
bucket = new List<Account>();
accountsByIndustry.put(a.Industry, bucket);
}
bucket.add(a);
}Keep these key behaviors in mind:
- String keys are case-sensitive in a Map.
'Energy'and'energy'are two groups. If the data is inconsistent, normalize the key first, for example withtoLowerCase(). - Apex allows a
nullkey. Accounts with no Industry all land in one group undernull. That does not fail, but it may hide records you meant to handle separately. - If a record's key is
nulland you did not intend that, skip it explicitly, asContactGrouperdoes withcontinue.
Map of Lists or a relationship subquery
SOQL can return children nested under parents:
for (Account a : [
SELECT Id, Name, (SELECT Id, LastName FROM Contacts)
FROM Account
LIMIT 10
]) {
System.debug(a.Name + ': ' + a.Contacts.size());
}The subquery is shorter when you control the query and the parent-child relationship exists. The Map of Lists is better in these cases:
| Situation | Better choice |
|---|---|
| Children already arrive as a flat list, for example from `Trigger.new` | Map of Lists |
| Grouping key is not a lookup or master-detail relationship, such as Industry | Map of Lists |
| Grouping key combines fields or is computed | Map of Lists |
| Parent and children come from one query on a real relationship | Subquery |
The child query and parent query inside a subquery also share limits on the number of rows returned, so check the limits chapter when volumes are high.
Common errors
- NullPointerException on
get(key).add(...). The list for that key was never created. Create andputit first. - Empty map after the loop. The list was built in a variable but never stored with
put. - NullPointerException when reading a group.
getreturnednullfor a key with no records. UsecontainsKey, or fall back to a new empty list. - Surprising
nullgroup. Records with a blank key were grouped undernull. Filter them or handle that key on purpose. - Case-split groups. Strings that differ only by case became separate keys.
Check your understanding
Exercise
A trigger handler receives List<Opportunity> opps. Write the loop that builds Map<Id, List<Opportunity>> oppsByAccount, skipping opportunities with no AccountId. Then explain what oppsByAccount.get(someId) returns for an account that has no opportunities in opps, and how to read it safely.
Show answer
Loop: Map<Id, List<Opportunity>> oppsByAccount = new Map<Id, List<Opportunity>>(); for (Opportunity o : opps) { if (o.AccountId == null) { continue; } List<Opportunity> bucket = oppsByAccount.get(o.AccountId); if (bucket == null) { bucket = new List<Opportunity>(); oppsByAccount.put(o.AccountId, bucket); } bucket.add(o); }. For an account with no opportunities in opps, get returns null because the key was never added. Reading it safely means checking oppsByAccount.containsKey(someId) first, or using oppsByAccount.containsKey(someId) ? oppsByAccount.get(someId) : new List<Opportunity>(), so the code never calls size() or iterates over null.