Intermediate 25 min read

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>> means: for each String key (a category), the value is itself a List<String> (the products in that category) — 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');

Before adding to the nested List, this checks whether the key already has one — if not, it creates an empty List first. Skipping this check and calling .add() on a key that was never put() would return null (from the previous lesson) and throw a NullPointerException trying 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');
}

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.

APEX

Nested Collections Quiz

1. Before calling .add() on a nested List retrieved from a Map, what should you check first?

Log in to submit the quiz and save your score.

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.