Sub topic 6
Maps: key-value lookup
A Map stores values under keys and returns a value when you give it the matching key. This chapter explains how a Map behaves, how to create one, and the mistakes that come up most often. It assumes you know basic Apex syntax (variables, loops, conditionals) and have met Lists and Sets. It also assumes you know what SObjects such as Account and Contact are, and can read a basic SOQL query.
What a Map is
A Map is a collection of key-value pairs. Each key appears at most once, and each key points to one value. The declaration names both types: Map<String, Integer> has String keys and Integer values.
Use a Map when you need to find an item by something other than its position. A List finds items by index, and a Set only answers "is this value present?". A Map answers "what belongs to this key?".
| Question you need to answer | Collection |
|---|---|
| What is the third item? | List |
| Have I seen this value already? | Set |
| What is the value for this key? | Map |
Creating a Map
You can create an empty Map and fill it later, or create it with initial pairs. The literal syntax uses => between each key and value.
Map<String, Integer> stock = new Map<String, Integer>();
stock.put('apple', 10);
stock.put('pear', 4);
Map<String, Integer> prices = new Map<String, Integer>{
'apple' => 3,
'pear' => 5
};
System.debug(stock.get('apple')); // 10
System.debug(prices.get('pear')); // 5
System.debug(stock.size()); // 2Keys and values can be any type. That includes primitives, SObjects, custom classes, and other collections. Keys are most often Strings or Ids. Values are often SObjects or Lists.
A third constructor builds a Map from a List of SObjects. It is covered in the chapter on using collections with SOQL. This is the short form:
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 10]
);Apex uses each record's Id as its key.
Key uniqueness and put
A Map holds one value per key. Calling put with a key that already exists replaces the old value. put returns the value it replaced, or null if the key was new.
Map<String, Integer> stock = new Map<String, Integer>{ 'apple' => 10 };
Integer previous = stock.put('apple', 12);
System.debug(previous); // 10
System.debug(stock.get('apple')); // 12
System.debug(stock.size()); // 1
Integer none = stock.put('plum', 7);
System.debug(none); // null
System.debug(stock.size()); // 2Replacing is silent. If two records can share a key, a plain put loses data without any error. When that is possible, store a List per key instead. The chapter on grouping records with a Map of Lists shows how.
Looking up values: get returns null
When a key is missing, get returns null. It does not throw an exception.
Map<String, Integer> stock = new Map<String, Integer>{ 'apple' => 10 };
System.debug(stock.get('apple')); // 10
System.debug(stock.get('plum')); // nullThis is safe until you treat the result as a primitive. Arithmetic on a null Integer throws a System.NullPointerException.
Map<String, Integer> stock = new Map<String, Integer>{ 'apple' => 10 };
// Throws System.NullPointerException because get('plum') is null.
// Integer total = stock.get('plum') + 1;
// Safe version: check first.
Integer current = stock.get('plum');
Integer total = (current == null) ? 1 : current + 1;
System.debug(total); // 1Apex has no "get with default" method, so the null check is the standard pattern. Use it whenever a missing key is possible.
get versus containsKey
A key can exist with a null value. In that case get returns null for both a missing key and a stored null, so it cannot tell the two cases apart. containsKey can.
Map<String, String> notes = new Map<String, String>();
notes.put('draft', null);
System.debug(notes.get('draft')); // null
System.debug(notes.get('final')); // null
System.debug(notes.containsKey('draft')); // true
System.debug(notes.containsKey('final')); // falseCall containsKey when the difference matters. If values are never null, comparing the result of get with null is enough.
How keys are compared
A Map decides whether two keys are the same by comparing their values. The rules depend on the key type:
- String keys are case-sensitive.
'Ada'and'ada'are different keys. - Id keys should be declared as
Id, notString. Apex then handles the Id format for you. If you use String keys for Ids, a 15-character and an 18-character form of the same Id will not match. - Null is a legal key.
put(null, value)works, andget(null)returns that value. This is rarely intended, so a null key usually signals a bug upstream.
Map<String, String> roles = new Map<String, String>{ 'Ada' => 'Engineer' };
System.debug(roles.get('Ada')); // Engineer
System.debug(roles.get('ada')); // null
System.debug(roles.containsKey('ADA')); // falseTo make lookups case-insensitive, normalize every key the same way, both when you put and when you get:
Map<String, String> roles = new Map<String, String>();
roles.put('Ada'.toLowerCase(), 'Engineer');
String lookupName = 'ADA';
System.debug(roles.get(lookupName.toLowerCase())); // EngineerOrder is not guaranteed
Do not rely on the order in which a Map returns its keys or values. Two Maps with the same pairs may list them in different orders. If you need a predictable order, copy the keys into a List and sort it:
Map<String, Integer> stock = new Map<String, Integer>{
'pear' => 4,
'apple' => 10,
'fig' => 2
};
List<String> keys = new List<String>(stock.keySet());
keys.sort();
System.debug(keys); // (apple, fig, pear)keySet() returns a Set of the keys. values() returns a List of the values. The chapter on Map methods covers both.
Values are references
When the value is an SObject or another object, the Map stores a reference to it, not a copy. get returns that same object, so changing it through the returned reference changes what the Map holds.
Map<String, Account> byName = new Map<String, Account>{
'Acme' => new Account(Name = 'Acme', Industry = 'Retail')
};
Account a = byName.get('Acme');
a.Industry = 'Energy';
System.debug(byName.get('Acme').Industry); // EnergyThis is convenient, because you can update records in place and then send them to DML. It also means two variables can point to the same record. The chapter on references, clone, and deepClone covers copying.
Common mistakes
- Using the result of
getwithout a null check. Arithmetic or method calls on a missing value throwNullPointerException. - Overwriting values by accident. Two records with the same key replace each other. Check
containsKeyfirst, or use a Map of Lists. - Mixing String and Id keys. A Map typed with
Stringkeys will not match Ids the way anId-keyed Map does. - Depending on key order. Sort the keys when order matters.
- Mismatched key case. Normalize String keys when the source data is not consistent.
Exercise
A Map<String, Integer> named scores contains the pair 'Ada' => 90. What do scores.get('ada') and scores.containsKey('ada') return, and how would you make a lookup for 'ada' find Ada's score?
Show answer
Both fail to find the key. scores.get('ada') returns null and scores.containsKey('ada') returns false, because String keys are case-sensitive. To make the lookup work, normalize the keys. Store each key with toLowerCase() when you call put, and call toLowerCase() on the search string before you call get.
Exercise
This code throws an exception when 'plum' is not in the Map. Fix it so it adds 1 to the count when the key exists, and sets the count to 1 when it does not. Map<String, Integer> counts = new Map<String, Integer>{ 'apple' => 2 }; counts.put('plum', counts.get('plum') + 1);
Show answer
counts.get('plum') is null, and adding 1 to null throws a NullPointerException. Read the value into a variable and check it:
Integer current = counts.get('plum');
counts.put('plum', current == null ? 1 : current + 1);
Checking counts.containsKey('plum') first also works.