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
  1. Map<String, Decimal> productPrices = new Map<String, Decimal>(); — Map<String, Decimal> declares a map from String keys to Decimal values.
  2. productPrices.put('Widget', 49.99); — put(key, value) adds an entry.
  3. productPrices.put('Gadget', 89.99); — adds another.
  4. (blank line)
  5. System.debug(productPrices.get('Widget')); — get(key) retrieves the value for that key directly — no looping required — logs 49.99.

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.');
}
  1. Map<String, Decimal> productPrices = new Map<String, Decimal>{'Widget' => 49.99}; — a map with only one entry.
  2. (blank line)
  3. if (productPrices.containsKey('Gadget')) { — containsKey() checks safely first, exactly the guard-before-use habit from Module 12's "Handle Errors Gracefully" lesson.
  4. System.debug(productPrices.get('Gadget')); — only reached if the key exists.
  5. } else { — the key doesn't exist here.
  6. System.debug('No price found for Gadget.'); — a clean fallback, instead of calling get() on a key that doesn't exist and silently getting null back — which could lead to a confusing NullPointerException later.
  7. } — closes the if/else.

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'));
  1. // The List approach: search every item, one at a time — the label for what follows.
  2. for (Product__c p : allProducts) { — searching a List means checking items one by one.
  3. if (p.Name == 'Widget') { — until a match is found.
  4. System.debug(p.Price__c); — logs it.
  5. break; — stops searching once found.
  6. } — closes the if.
  7. } — closes the loop — slower as the list grows.
  8. (blank line)
  9. // The Map approach: direct lookup, no searching — the label for the alternative.
  10. System.debug(productPrices.get('Widget')); — a Map looks a key up directly — 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);

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

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.