Sub topic 7
Working with Map methods
This chapter assumes you can write basic Apex, know what a Map is (a collection of key-value pairs with unique keys), and have seen a SOQL query returned into a collection. Here you will learn the methods you use most often and the mistakes that go with them.
The core methods
| Method | What it does | Returns |
|---|---|---|
| `put(key, value)` | Adds a pair, or replaces the value if the key exists | The previous value, or `null` |
| `get(key)` | Reads the value for a key | The value, or `null` if the key is missing |
| `containsKey(key)` | Checks whether a key exists | `Boolean` |
| `remove(key)` | Deletes a pair | The removed value, or `null` |
| `size()` / `isEmpty()` | Count the pairs / check for zero pairs | `Integer` / `Boolean` |
| `keySet()` | Gets all keys | `Set` of the key type |
| `values()` | Gets all values | `List` of the value type |
| `putAll(other)` | Copies every pair from another map or from a list of SObjects | `void` |
| `clear()` | Removes all pairs | `void` |
Adding, reading, and removing
Map<String, Integer> stock = new Map<String, Integer>();
stock.put('pen', 10);
Integer previous = stock.put('pen', 12); // replaces the value, returns 10
stock.put('ink', 4);
System.debug(previous); // 10
System.debug(stock.get('pen')); // 12
System.debug(stock.containsKey('cap')); // false
System.debug(stock.get('cap')); // null
Integer removed = stock.remove('ink'); // 4
System.debug(stock.size()); // 1
System.debug(stock.isEmpty()); // falseA second put with an existing key never creates a duplicate. It overwrites the old value.
Reading all keys and values
keySet() and values() give you the contents as a Set and a List. Do not rely on their order, because a map does not promise one.
Map<String, Integer> stock = new Map<String, Integer>{
'pen' => 12,
'cap' => 7
};
Map<String, Integer> extra = new Map<String, Integer>{
'cap' => 9,
'tape' => 3
};
stock.putAll(extra); // 'cap' is overwritten with 9, 'tape' is added
Set<String> keys = stock.keySet();
List<Integer> counts = stock.values();
System.debug(keys.size()); // 3
System.debug(counts.size()); // 3
System.debug(stock.get('cap')); // 9putAll follows the same rule as put. When both maps have a key, the incoming value wins.
Common errors
- Treating
nullas "missing".getreturnsnullfor an absent key, but it also returnsnullwhen the key exists and holdsnull. UsecontainsKeywhen that difference matters. - Calling a method on a missing value.
map.get(k).add(x)throws aNullPointerExceptionwhenkis absent. CheckcontainsKeyfirst and create the value, as in the grouping pattern from the previous chapters. - Case-sensitive String keys.
'Pen'and'pen'are different keys. Normalize withtoLowerCase()before you callputandget. - Expecting order. Do not use
keySet()orvalues()when the order of results matters. Sort aListcopy instead.
Maps built from SOQL
When you pass a SOQL result to the Map constructor, the keys are the record Ids. You can also call putAll with a list of records, which adds each one under its Id.
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 10]
);
List<Account> more = [SELECT Id, Name FROM Account WHERE Name LIKE 'A%' LIMIT 5];
accountsById.putAll(more); // existing Ids are overwritten, new ones added
for (Id accId : accountsById.keySet()) {
System.debug(accountsById.get(accId).Name);
}Exercise
A map Map<String, Integer> m contains the pair 'x' => 5. What do m.put('x', 8) and m.remove('y') return, and what is m.size() afterwards?
Show answer
m.put('x', 8) returns 5, the previous value, and replaces it with 8. m.remove('y') returns null because 'y' is not a key, and the map is unchanged. m.size() is 1.