Intermediate 25 min read

Maps

By the end of this lesson, you'll be able to:

  • Declare and initialize a Map with a key type and a value type
  • Add, retrieve, and check for the existence of a key
  • Explain why a Map lookup by key is faster than searching a List

Prerequisites: "Sets"

Declaring and populating a Map

Map<String, Decimal> productPrices = new Map<String, Decimal>();
productPrices.put('Widget', 49.99);
productPrices.put('Gadget', 89.99);

System.debug(productPrices.get('Widget')); // 49.99

Map<String, Decimal> declares a map from String keys to Decimal values. put(key, value) adds or updates an entry; get(key) retrieves the value for that key directly — no looping required.

Checking for a key before using it

Map<String, Decimal> productPrices = new Map<String, Decimal>{'Widget' => 49.99};

if (productPrices.containsKey('Gadget')) {
    System.debug(productPrices.get('Gadget'));
} else {
    System.debug('No price found for Gadget.');
}

Calling get() on a key that doesn't exist returns null rather than throwing an error — but relying on that silently can lead to confusing NullPointerExceptions later. containsKey() checks safely first, exactly the guard-before-use habit from Module 12's "Handle Errors Gracefully" lesson.

Why a Map beats searching a List

// The List approach: search every item, one at a time
for (Product__c p : allProducts) {
    if (p.Name == 'Widget') {
        System.debug(p.Price__c);
        break;
    }
}

// The Map approach: direct lookup, no searching
System.debug(productPrices.get('Widget'));

Searching a List for a matching item means checking items one by one until you find it (or don't) — slower as the list grows. A Map looks a key up directly, which is why "look this up by Id" is almost always modeled as a Map in real Apex code, especially inside loops where repeated searching would be costly.

Exercise

Build a Map<String, Integer> called stockLevels with three products and their stock counts. Debug the stock level for one of them using get().

Show hint

stockLevels.put('Widget', 40);

APEX

Maps Quiz

1. What does calling get() on a Map for a key that doesn't exist return?

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

A Map stores key-value pairs, letting you look up a value directly by its key instead of searching through a list one item at a time.