Sub topic 6
Maps: key-value lookup
This chapter assumes you know basic Apex syntax, have used Lists and Sets, and can read a simple SOQL query. A Map stores pairs of a key and a value. It is the right choice when you need to find a value quickly by a known key.
What a Map is
A Map is a collection where each key appears once and points to one value. You declare both types: Map<KeyType, ValueType>. Keys are unique. Values can repeat. If you put a value under a key that already exists, the new value replaces the old one.
Compare the three collection types:
| Type | Order | Duplicates | Access by |
|---|---|---|---|
| List | Kept | Allowed | Index |
| Set | Not guaranteed | Not allowed | Contains check |
| Map | Not guaranteed | Keys: no. Values: yes | Key |
Counting with a Map
The code below counts how often each word appears. get returns null when the key is missing, so the code checks for null before it increments.
List<String> words = new List<String>{'a', 'b', 'a'};
Map<String, Integer> counts = new Map<String, Integer>();
for (String w : words) {
Integer current = counts.get(w);
counts.put(w, current == null ? 1 : current + 1);
}
System.debug(counts.get('a')); // 2
System.debug(counts.get('z')); // nullA null result is ambiguous when null is also a valid stored value. In that case, call containsKey to tell the two cases apart.
Building a Map from a SOQL query
The Map constructor accepts a list of records. It uses each record's Id as the key and the record as the value. You get a lookup table without writing a loop.
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 10]
);
Set<Id> accountIds = accountsById.keySet();
List<Contact> contacts = [
SELECT Id, LastName, AccountId
FROM Contact
WHERE AccountId IN :accountIds
];keySet() returns a Set<Id>. You can pass it straight into an IN bind variable, as the last query shows. This constructor works only for keys of type Id. For any other key, such as a name or an external ID, build the Map with a loop and put.
Common mistakes
- Treating
getas if it throws on a missing key. It returnsnull, and calling a method on that result throws aNullPointerException. - Assuming a fixed iteration order. Do not rely on the order of keys or values.
- Using a mutable object as a key. Stick to primitives and Ids.
- Forgetting that
putoverwrites. When one key must hold many values, use a Map of Lists, which a later chapter covers.
Exercise
A Map<String, Integer> named scores has no entry for 'Ada'. What does scores.get('Ada') return, and how can you check for the key without risking a null value being misread?
Show answer
It returns null. Call scores.containsKey('Ada'), which returns false when the key is absent. This separates a missing key from a key whose stored value is null.