Sub topic 11
Nested collections
This chapter assumes you can create Lists, Sets, and Maps and call their basic methods. You should also be comfortable with for loops and with the difference between a missing key and a null value in a Map. The next chapter applies nested collections to group records. Here we cover the mechanics: declaring them, filling them safely, reading them, and avoiding the errors they invite.
What a nested collection is
A nested collection is a collection whose elements are themselves collections. Apex lets you use any collection type as the element type of a List or Set, or as the value type of a Map. The type name spells out the structure from the outside in.
| Type | Meaning |
|---|---|
| `List<List<Integer>>` | A list of rows, where each row is a list of integers. |
| `Map<String, List<String>>` | Each key maps to an ordered list of strings. |
| `Map<String, Set<String>>` | Each key maps to a set of unique strings. |
| `Map<String, Map<String, Integer>>` | Each key maps to another map, giving a two-level lookup. |
Choose the inner type with the same rules you use for a single collection. Use a List when order or duplicates matter. Use a Set when each value should appear once. Use a Map when you need lookup by key.
Declaring and initializing
Each level needs its own new. Declaring the outer collection does not create the inner ones.
List<List<Integer>> grid = new List<List<Integer>>();
for (Integer r = 0; r < 3; r++) {
List<Integer> row = new List<Integer>();
for (Integer c = 0; c < 3; c++) {
row.add(r * 3 + c);
}
grid.add(row);
}
System.debug(grid.get(1).get(2)); // 5
System.debug(grid.size()); // 3
System.debug(grid.get(0).size()); // 3Literal syntax also works at each level. Every inner collection is its own new expression.
Map<String, List<String>> skills = new Map<String, List<String>>{
'Ada' => new List<String>{ 'math', 'code' },
'Grace' => new List<String>{ 'compilers' }
};
System.debug(skills.get('Ada').get(1)); // code
System.debug(skills.get('Grace').size()); // 1Chained calls such as skills.get('Ada').get(1) read from left to right. skills.get('Ada') returns the inner List, and .get(1) reads from that List.
The inner collection does not exist until you create it
The most common error with nested collections is a System.NullPointerException. Map.get returns null for a missing key, so chaining a method onto it fails.
Map<String, List<String>> skills = new Map<String, List<String>>();
// Throws System.NullPointerException: there is no list for 'Linus' yet.
skills.get('Linus').add('kernels');The fix is a put-if-absent step. Check for the key, create the inner collection if it is missing, and then use it.
Map<String, List<String>> skills = new Map<String, List<String>>();
String person = 'Linus';
if (!skills.containsKey(person)) {
skills.put(person, new List<String>());
}
skills.get(person).add('kernels');
skills.get(person).add('version control');
System.debug(skills); // {Linus=(kernels, version control)}Use containsKey for this check. Checking get(key) == null also works for inner collections, because you never store null as a value. containsKey states the intent more clearly, and it stays correct if a map can hold null values.
Inner collections are references
Map.get does not return a copy of the inner collection. It returns a reference to the same object that is stored in the map. Changing the inner collection changes what the map holds, and you do not need to call put again.
Map<String, List<String>> skills = new Map<String, List<String>>{
'Ada' => new List<String>{ 'math' }
};
List<String> adaSkills = skills.get('Ada');
adaSkills.add('code');
System.debug(skills.get('Ada')); // (math, code)This behavior is why the put-if-absent pattern needs put only once, when the inner collection is created. It also means two keys can accidentally share one inner collection.
List<String> shared = new List<String>{ 'math' };
Map<String, List<String>> skills = new Map<String, List<String>>{
'Ada' => shared,
'Grace' => shared
};
skills.get('Ada').add('code');
System.debug(skills.get('Grace')); // (math, code), the same listCreate a fresh inner collection for each key unless you intend to share. The later chapter on clone and deepClone covers how to copy nested structures.
Two-level maps
A Map<String, Map<String, Integer>> gives you a lookup by two keys, such as region and then product. The put-if-absent step happens at the outer level, and the inner map then follows the usual counting pattern.
Map<String, Map<String, Integer>> unitsByRegion = new Map<String, Map<String, Integer>>();
List<String> regions = new List<String>{ 'EMEA', 'EMEA', 'APAC', 'EMEA' };
List<String> products = new List<String>{ 'Widget', 'Gadget', 'Widget', 'Widget' };
for (Integer i = 0; i < regions.size(); i++) {
String region = regions[i];
String product = products[i];
if (!unitsByRegion.containsKey(region)) {
unitsByRegion.put(region, new Map<String, Integer>());
}
Map<String, Integer> byProduct = unitsByRegion.get(region);
Integer current = byProduct.get(product);
byProduct.put(product, current == null ? 1 : current + 1);
}
System.debug(unitsByRegion.get('EMEA').get('Widget')); // 2
System.debug(unitsByRegion.get('APAC').get('Widget')); // 1Reading a two-level map has the same trap as writing to one. unitsByRegion.get('LATAM').get('Widget') throws a NullPointerException, because the LATAM key is missing. When a key might be absent, check with containsKey before the second get.
Integer units = 0;
if (unitsByRegion.containsKey('LATAM')
&& unitsByRegion.get('LATAM').containsKey('Widget')) {
units = unitsByRegion.get('LATAM').get('Widget');
}
System.debug(units); // 0Iterating over nested collections
Nested loops mirror the nesting. Iterate the outer collection first, then the inner collection you get from each element.
for (String region : unitsByRegion.keySet()) {
Map<String, Integer> byProduct = unitsByRegion.get(region);
for (String product : byProduct.keySet()) {
System.debug(region + ' / ' + product + ' = ' + byProduct.get(product));
}
}To walk only the inner collections, iterate values(). This example flattens a Map<String, Set<String>> into one Set of every tag, and the Set removes duplicates across the groups.
Map<String, Set<String>> tagsByAuthor = new Map<String, Set<String>>{
'Ada' => new Set<String>{ 'apex', 'soql' },
'Grace' => new Set<String>{ 'apex', 'trigger' }
};
Set<String> allTags = new Set<String>();
for (Set<String> tags : tagsByAuthor.values()) {
allTags.addAll(tags);
}
System.debug(allTags.size()); // 3Each level of nesting adds a loop, and the work grows with the product of the sizes. A loop inside a loop over two collections of 200 elements runs 40,000 iterations. Prefer a map lookup over an inner loop when you only need to find one element.
A built-in example: SOSL results
SOSL queries return a List<List<SObject>>. There is one inner list for each object type in the RETURNING clause, in the order you wrote them. You cast each inner list to the concrete type.
List<List<SObject>> results = [
FIND 'Acme' IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, LastName)
];
List<Account> accounts = (List<Account>) results[0];
List<Contact> contacts = (List<Contact>) results[1];
System.debug(accounts.size() + ' accounts, ' + contacts.size() + ' contacts');Choosing the nesting
Deep nesting makes code hard to read. A few guidelines help.
- Stop at two levels. If you need a third, consider a small class that holds the related data in named fields.
- Pick the inner type for the question you will ask. Use a Set to ask "is this value present?" and a List to preserve order or keep duplicates.
- Keep Ids as keys when you can.
Map<Id, Set<Id>>is compact and works well with SOQL bind variables. - Remember that nested structures use more heap than flat ones, since each inner collection is a separate object.
Exercise
You have a Map<String, Set<String>> membersByTeam. Write the code that adds the member 'Ada' to the team 'Platform', so that it works whether or not 'Platform' is already a key. Then explain why you do not need to call put again after adding to the Set.
Show answer
if (!membersByTeam.containsKey('Platform')) {
membersByTeam.put('Platform', new Set<String>());
}
membersByTeam.get('Platform').add('Ada');
The first put stores the new Set in the map once. get returns a reference to that same Set, not a copy, so add changes the Set the map already holds. A second put is unnecessary. Because the inner collection is a Set, adding 'Ada' twice leaves a single entry.