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']
  1. Map<String, List<String>> productsByCategory = new Map<String, List<String>>(); — Map<String, List<String>> means: for each String key (a category), the value is itself a List<String> (the products in that category).
  2. productsByCategory.put('Electronics', new List<String>{'Laptop', 'Phone'}); — associates a whole list with one key.
  3. productsByCategory.put('Furniture', new List<String>{'Desk', 'Chair'}); — and a different list with another key.
  4. (blank line)
  5. List<String> electronics = productsByCategory.get('Electronics'); — retrieves the nested list.
  6. 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');
  1. Map<String, List<String>> productsByCategory = new Map<String, List<String>>(); — starts empty.
  2. (blank line)
  3. String category = 'Electronics'; — the category being added to.
  4. if (! productsByCategory.containsKey(category)) { — checks whether the key already has a list.
  5. productsByCategory.put(category, new List<String>()); — if not, creates an empty List first.
  6. } — closes the if.
  7. productsByCategory.get(category).add('Tablet'); — only now is it safe to add — skipping the 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');
}
  1. Map<String, List<String>> lessonsByModule = new Map<String, List<String>>{ — a nested collection built directly with a map literal.
  2. 'Collections: Lists' => new List<String>{'What Is a Collection?', 'Lists', 'Iterating Lists', 'Sorting Lists'}, — one module's lessons.
  3. 'Collections: Sets and Maps' => new List<String>{'Sets', 'Maps'} — another module's lessons.
  4. }; — closes the map literal.
  5. (blank line)
  6. for (String moduleName : lessonsByModule.keySet()) { — keySet() returns every key, so the loop can visit each module by name.
  7. System.debug(moduleName + ' has ' + lessonsByModule.get(moduleName).size() + ' lessons'); — looks up each module's lesson list and reports its size.
  8. } — 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.

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

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.