Nested Collections
By the end of this lesson, you'll be able to:
- Declare a collection whose values are themselves collections
- Read and write to a nested collection safely
- Recognize a real scenario where nested collections are the natural fit
Prerequisites: "Maps of sObjects"
A Map of Lists
Map<String, List<String>> productsByCategory = new Map<String, List<String>>();
productsByCategory.put('Electronics', new List<String>{'Laptop', 'Phone'});
productsByCategory.put('Furniture', new List<String>{'Desk', 'Chair'});
List<String> electronics = productsByCategory.get('Electronics');
System.debug(electronics); // ['Laptop', 'Phone']
Map<String, List<String>> productsByCategory = new Map<String, List<String>>();—Map<String, List<String>>means: for eachStringkey (a category), the value is itself aList<String>(the products in that category).productsByCategory.put('Electronics', new List<String>{'Laptop', 'Phone'});— associates a whole list with one key.productsByCategory.put('Furniture', new List<String>{'Desk', 'Chair'});— and a different list with another key.- (blank line)
List<String> electronics = productsByCategory.get('Electronics');— retrieves the nested list.System.debug(electronics);— logs['Laptop', 'Phone']— a natural shape for "group items by category."
Safely adding to a nested List
Map<String, List<String>> productsByCategory = new Map<String, List<String>>();
String category = 'Electronics';
if (! productsByCategory.containsKey(category)) {
productsByCategory.put(category, new List<String>());
}
productsByCategory.get(category).add('Tablet');
Map<String, List<String>> productsByCategory = new Map<String, List<String>>();— starts empty.- (blank line)
String category = 'Electronics';— the category being added to.if (! productsByCategory.containsKey(category)) {— checks whether the key already has a list.productsByCategory.put(category, new List<String>());— if not, creates an emptyListfirst.}— closes theif.productsByCategory.get(category).add('Tablet');— only now is it safe to add — skipping the check and calling.add()on a key that was neverput()would returnnull(from the previous lesson) and throw aNullPointerExceptiontrying to call.add()on it.
A real business example: Course Catalog
Map<String, List<String>> lessonsByModule = new Map<String, List<String>>{
'Collections: Lists' => new List<String>{'What Is a Collection?', 'Lists', 'Iterating Lists', 'Sorting Lists'},
'Collections: Sets and Maps' => new List<String>{'Sets', 'Maps'}
};
for (String moduleName : lessonsByModule.keySet()) {
System.debug(moduleName + ' has ' + lessonsByModule.get(moduleName).size() + ' lessons');
}
Map<String, List<String>> lessonsByModule = new Map<String, List<String>>{— a nested collection built directly with a map literal.'Collections: Lists' => new List<String>{'What Is a Collection?', 'Lists', 'Iterating Lists', 'Sorting Lists'},— one module's lessons.'Collections: Sets and Maps' => new List<String>{'Sets', 'Maps'}— another module's lessons.};— closes the map literal.- (blank line)
for (String moduleName : lessonsByModule.keySet()) {—keySet()returns every key, so the loop can visit each module by name.System.debug(moduleName + ' has ' + lessonsByModule.get(moduleName).size() + ' lessons');— looks up each module's lesson list and reports its size.}— closes the loop.
This course's own structure is naturally a nested collection: a course has modules, and each module has a list of lessons — exactly the "group of groups" shape nested collections exist for.
Exercise
Build a Map<String, List<Integer>> called scoresByStudent with two students, each with a List of 2-3 quiz scores. Debug the average score for one student.
Show hint
Loop over the List for one key and divide the sum by its size.
Nested Collections Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Collections can hold other collections as their values — like a Map of Lists, useful whenever data naturally groups into categories, each containing multiple items.