Sub topic 7
Working with Map methods
This chapter assumes you know Apex variables, loops, and conditionals, and that you have seen the Map syntax from the previous chapter. It covers the methods you use most often, what each one returns, and the mistakes that follow from those return values. Run the examples in Anonymous Apex with debug logs open.
The core methods
A Map<K, V> stores one value per unique key. The table lists the methods you will use most.
| Method | Returns | Behavior |
|---|---|---|
| `put(key, value)` | the previous value, or `null` | Adds the pair or replaces the value for an existing key |
| `get(key)` | the value, or `null` | Reads the value for a key |
| `containsKey(key)` | `Boolean` | Tests whether the key exists, even if its value is `null` |
| `remove(key)` | the removed value, or `null` | Deletes the pair |
| `keySet()` | `Set<K>` | All keys |
| `values()` | `List<V>` | All values, in no guaranteed order |
| `size()` | `Integer` | Number of pairs |
| `isEmpty()` | `Boolean` | `true` when there are no pairs |
| `putAll(...)` | nothing | Copies in pairs from another map, or records from a list |
| `clear()` | nothing | Removes every pair |
Adding, replacing, and removing
put does two jobs. It inserts a new pair, or it overwrites the value if the key already exists. In both cases it returns whatever was stored before, which is null for a new key.
Map<String, Integer> stock = new Map<String, Integer>{
'apple' => 5,
'pear' => 2
};
Integer previous = stock.put('apple', 7); // 5, the old value
Integer none = stock.put('plum', 1); // null, new key
Integer removed = stock.remove('pear'); // 2
Integer missing = stock.remove('kiwi'); // null, nothing to remove
System.debug(previous); // 5
System.debug(none); // null
System.debug(removed); // 2
System.debug(missing); // null
System.debug(stock.size()); // 2Because put overwrites silently, a second put with the same key loses the first value. If you meant to keep both, you need a Map of List values, which a later chapter covers.
Reading with get
get returns null when the key is absent. It also returns null when the key is present and its value is null. The two cases look the same from get alone.
Map<String, String> phone = new Map<String, String>();
phone.put('Ada', null);
System.debug(phone.get('Ada')); // null, key exists
System.debug(phone.get('Grace')); // null, key missing
System.debug(phone.containsKey('Ada')); // true
System.debug(phone.containsKey('Grace')); // falseUse containsKey when the difference matters. Use a null check on the result of get when it does not, because it saves a second lookup.
Counting with a default
Apex has no built-in "get with default" for this pattern, so you check for null yourself. This is the same shape as the counting example from the Map overview.
List<String> stages = new List<String>{'Open', 'Closed', 'Open', 'Open'};
Map<String, Integer> countByStage = new Map<String, Integer>();
for (String stage : stages) {
Integer current = countByStage.get(stage);
countByStage.put(stage, current == null ? 1 : current + 1);
}
System.debug(countByStage.get('Open')); // 3
System.debug(countByStage.get('Closed')); // 1If you wrote countByStage.get(stage) + 1 without the check, the first occurrence would throw a System.NullPointerException, because null + 1 is not allowed.
Keys and values as collections
keySet() returns a Set<K> and values() returns a List<V>. These are separate copies of the key and value data. Changing the returned set or list does not change the map.
Map<String, Integer> scores = new Map<String, Integer>{
'Ada' => 90,
'Grace' => 85,
'Linus' => 70
};
Set<String> people = scores.keySet();
List<Integer> allScores = scores.values();
Integer total = 0;
for (Integer s : allScores) {
total += s;
}
System.debug(people.contains('Ada')); // true
System.debug(total); // 245Neither collection has a guaranteed order. If you need a stable order, copy the keys into a list and sort it.
List<String> sortedNames = new List<String>(scores.keySet());
sortedNames.sort();
for (String name : sortedNames) {
System.debug(name + ': ' + scores.get(name));
}A Set passed to the List constructor is a common way to convert between the two types.
Combining maps with putAll
putAll copies every pair from another map into this one. Keys that exist in both maps take the value from the argument.
Map<String, Integer> base = new Map<String, Integer>{'a' => 1, 'b' => 2};
Map<String, Integer> extra = new Map<String, Integer>{'b' => 20, 'c' => 30};
base.putAll(extra);
System.debug(base.get('a')); // 1
System.debug(base.get('b')); // 20, overwritten
System.debug(base.get('c')); // 30For a map whose keys are Id and whose values are SObjects, putAll also accepts a list of records. Each record is keyed by its Id.
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 5]
);
accountsById.putAll(
[SELECT Id, Name FROM Account WHERE Name LIKE 'A%' LIMIT 5]
);
System.debug(accountsById.size());Records that appear in both queries share an Id, so they occupy one entry each. The map never holds duplicates.
Maps of SObjects hold references
The value stored in a map is a reference to the record, not a copy. When you call get and change a field, you change the record that the map holds.
Map<String, Account> accountsByName = new Map<String, Account>();
accountsByName.put('Acme', new Account(Name = 'Acme', Industry = 'Retail'));
Account found = accountsByName.get('Acme');
found.Industry = 'Energy';
System.debug(accountsByName.get('Acme').Industry); // EnergyThis is useful when you build up changes in a map and later pass accountsByName.values() to a DML statement. It is also a source of surprise if another variable points at the same record. The reference chapter later in this tutorial covers clone and deepClone, which control this behavior.
Keys: equality and case
Map keys are compared by value for primitive types. Two details catch people out.
Stringkeys are case-sensitive in a map.'acme'and'Acme'are different keys. Normalize withtoLowerCase()before callingputandgetif your data has inconsistent case.nullis a legal key.put(null, 'x')works, andget(null)returns'x'.
Map<String, Integer> visits = new Map<String, Integer>();
visits.put('Acme', 1);
System.debug(visits.containsKey('acme')); // false
System.debug(visits.containsKey('Acme')); // true
String normalized = 'ACME'.toLowerCase();
visits.put(normalized, 5);
System.debug(visits.size()); // 2Using an SObject as a key is possible but fragile. If you change a field on the record after using it as a key, the map may no longer find it. Prefer Id or a String field as the key.
Common errors
- Reading a missing key and using the result.
getreturnsnull, and calling a method on that result throws aNullPointerException. CheckcontainsKeyor compare withnullfirst. - Removing while iterating. Calling
removeon a map inside a loop over its ownkeySet()is risky. Collect the keys to remove in a separate list, then remove them after the loop. - Expecting insertion order.
keySet()andvalues()return items in no promised order. Sort a copy when order matters. - Overwriting by accident. Two records with the same key will collapse into one entry. Choose a key that is unique for your data.
- Passing a map where a collection is expected. A
Mapis not aListor aSet. A SOQL bind variable such asIN :accountIdsneeds the result ofkeySet()orvalues(), not the map itself.
Exercise
Exercise
A map Map<String, Integer> m = new Map<String, Integer>{'x' => 1}; runs the lines Integer a = m.put('x', 9); Integer b = m.put('y', 4); Integer c = m.remove('z');. What are the values of a, b, c, and m.size() afterward?
Show answer
a is 1, because put returns the previous value for 'x'. b is null, because 'y' was a new key. c is null, because 'z' does not exist, so remove has nothing to return. m.size() is 2, since the map holds 'x' (now 9) and 'y' (4).
Exercise
You have Map<String, String> emails and a key 'Ada' that was stored with a null value. Which check tells you whether 'Ada' is in the map: emails.get('Ada') != null or emails.containsKey('Ada')?
Show answer
Use emails.containsKey('Ada'). The get check returns null both for a missing key and for a key stored with a null value, so it cannot tell the two cases apart. containsKey returns true in this case.