Sub topic 10
Lists, sets, and maps
This chapter assumes you can declare variables, know the primitive types, and understand null (covered earlier). You can run every snippet as anonymous Apex in the Developer Console. The one snippet that queries data needs an org with Account records.
The three collection types
Apex has three built-in collection types. Each is generic, so you state the element type in angle brackets, such as List<String>.
| Type | Ordered | Duplicates | Access by | Typical use |
|---|---|---|---|---|
| `List<T>` | Yes, by index | Allowed | Zero-based index | Records in sequence, query results |
| `Set<T>` | No guaranteed order | Not allowed | `contains` | Unique values, fast membership tests |
| `Map<K, V>` | No guaranteed order | Keys unique, values may repeat | Key | Lookups by Id or name |
Lists
A list keeps elements in insertion order and addresses them by a zero-based index. You can use get(i) or array notation names[i].
List<String> names = new List<String>{ 'Ada', 'Grace' };
names.add('Ada');
names.add(0, 'Linus');
System.debug(names);
System.debug(names[1]);
System.debug(names.indexOf('Grace'));
names.sort();
System.debug(names);
System.debug(names.size());The output is (Linus, Ada, Grace, Ada), then Ada, then 2, then the sorted list (Ada, Ada, Grace, Linus), then 4.
Reading or writing outside the valid range throws a System.ListException with the message "List index out of bounds". Apex does not return null for a bad index. Check isEmpty() or size() before you read a position that may not exist.
List<String> empty = new List<String>();
if (!empty.isEmpty()) {
System.debug(empty[0]);
}
System.debug('Safe: no exception thrown');Sets
A set stores each value at most once. add returns a Boolean that tells you whether the set changed. Use a set when the question is "have I seen this value?"
Set<String> seen = new Set<String>{ 'Ada', 'Grace' };
System.debug(seen.add('Linus'));
System.debug(seen.add('Ada'));
System.debug(seen.contains('Grace'));
System.debug(seen.contains('grace'));
System.debug(seen.size());This prints true, false, true, false, 3.
contains('grace') is false because Set<String> compares elements case-sensitively. This differs from the == operator on strings, which ignores case. Map keys that are strings behave the same way as set elements. If you need case-insensitive matching, normalize with toLowerCase() before adding and before looking up.
A common idiom removes duplicates from a list by passing it to a set constructor:
List<String> raw = new List<String>{ 'a', 'b', 'a', 'c', 'b' };
Set<String> unique = new Set<String>(raw);
System.debug(unique.size());The result is 3. Do not rely on the iteration order of a set.
Maps
A map associates unique keys with values. put adds or overwrites. get returns the value, or null if the key is absent.
List<String> names = new List<String>{ 'Ada', 'Grace', 'Ada' };
Map<String, Integer> counts = new Map<String, Integer>();
for (String n : names) {
counts.put(n, (counts.get(n) ?? 0) + 1);
}
System.debug(counts.get('Ada'));
System.debug(counts.containsKey('Linus'));
System.debug(counts.keySet());
System.debug(counts.values());counts.get('Ada') returns 2. The ?? operator supplies 0 when the key is not yet present.
get returns null both for a missing key and for a key whose stored value is null. When that difference matters, call containsKey first.
keySet() returns a Set<K> and values() returns a List<V>. Neither has a guaranteed order.
Building a map from records
Maps keyed by record Id are one of the most common patterns in Apex. The Map constructor accepts a list of SObjects (or a SOQL query result) and keys each record by its Id:
Map<Id, Account> byId = new Map<Id, Account>([
SELECT Id, Name FROM Account LIMIT 5
]);
for (Id accId : byId.keySet()) {
System.debug(byId.get(accId).Name);
}This pattern lets you look up related records in constant time instead of scanning a list inside a loop.
Nested collections
A value can itself be a collection, which is how you group records by a field:
Map<String, List<String>> byInitial = new Map<String, List<String>>();
for (String n : new List<String>{ 'Ada', 'Alan', 'Grace' }) {
String key = n.substring(0, 1);
if (!byInitial.containsKey(key)) {
byInitial.put(key, new List<String>());
}
byInitial.get(key).add(n);
}
System.debug(byInitial.get('A'));The inner list must be created and stored before you call add on it. If you skip the containsKey check, byInitial.get(key) returns null and add throws a NullPointerException.
Reference behavior and final
Collections are reference types. Assigning one variable to another copies the reference, not the contents. Use clone() for a shallow copy.
List<Integer> a = new List<Integer>{ 1, 2 };
List<Integer> b = a;
b.add(3);
List<Integer> c = a.clone();
c.add(4);
System.debug(a.size());
System.debug(c.size());This prints 3 and 4. The variable b points at the same list as a, so adding through b changes a. The clone c is independent. The copy is shallow. If the list holds SObjects, both lists still point at the same records.
A final collection variable cannot be reassigned, but its contents can still change:
final List<String> log = new List<String>();
log.add('started');
System.debug(log.size());This works and prints 1. Writing log = new List<String>(); would be a compile error.
Common errors
- Reading
list[i]past the end throwsListException. - Calling a method on
map.get(key)without checking for a missing key throwsNullPointerException. - Assuming a set or map iterates in insertion order. It may not.
- Expecting
Set<String>.containsto ignore case. - Modifying a list while iterating over it with a for-each loop. This raises a runtime error. Build a second list of changes and apply it after the loop.
Exercise
A list items contains { 'x', 'y', 'x' }. What does new Set<String>(items).size() return, and what does items.size() return after that call?
Show answer
The set size is 2, because the duplicate 'x' is dropped. items.size() is still 3, because the set constructor copies the elements and does not change the list.
Exercise
Given Map<String, Integer> stock = new Map<String, Integer>{ 'pens' => 10 };, write one expression that returns 0 instead of null for the key 'staplers'.
Show answer
stock.get('staplers') ?? 0. The ?? operator returns the right side when the left side is null.
Exercise
Why does final List<String> names = new List<String>(); names.add('a'); compile and run?
Show answer
final prevents reassigning the variable to a different list, but it does not make the list read-only. add changes the contents of the same list object.