Sub topic 8
Iterating over Lists, Sets, and Maps
This chapter assumes you know Apex loop syntax, can create a List, Set, and Map, and know the core methods of each. If you haven't read the chapters on those methods, start there. Here you will learn which loop fits each collection, how to walk a Map, and which mistakes cause bugs or runtime errors.
The for-each loop is the default
Apex has several loop forms, but one handles most collection work: the collection-iteration loop, also called for-each. It works on Lists and Sets directly. A Map is not iterable, so you loop over one of its views instead.
List<String> names = new List<String>{'Ada', 'Grace', 'Linus'};
for (String n : names) {
System.debug(n);
}
Set<String> tags = new Set<String>{'apex', 'soql', 'trigger'};
for (String t : tags) {
System.debug(t);
}The variable before the colon takes each element in turn. Its type must match the element type, or be a type the element can be assigned to, such as Object or a parent SObject type.
For-each is the better choice when you don't need the position. You can't write off-by-one errors, and the loop reads the way you would describe it.
Indexed loops over Lists
A List is the only collection with positions, so only a List supports the traditional loop with a counter.
List<String> names = new List<String>{'Ada', 'Grace', 'Linus'};
for (Integer i = 0; i < names.size(); i++) {
System.debug(i + ': ' + names[i]);
}Use an indexed loop when you need one of these:
- The index itself, for example to number output rows.
- To compare neighbors, such as
names[i]andnames[i - 1]. - To remove elements while looping.
- To walk the List in reverse.
A Set has no index and no get(Integer) method, so an indexed loop is not possible. To loop over a Set by position, copy it into a List first with new List<String>(tags).
Iterating a Set
A Set loop visits every element exactly once. Apex does not guarantee the order, and the order can differ from the order you added elements. Never write logic that depends on it.
If you need a predictable order, copy the Set into a List and sort it:
Set<String> tags = new Set<String>{'soql', 'apex', 'trigger'};
List<String> ordered = new List<String>(tags);
ordered.sort();
for (String t : ordered) {
System.debug(t); // apex, soql, trigger
}Iterating a Map
A Map offers three views, and each suits a different job.
| Method | Returns | Use it when |
|---|---|---|
| `keySet()` | `Set` of keys | You need the keys, or the key and then the value |
| `values()` | `List` of values | You only care about the values |
| `get(key)` | One value or `null` | You already know the key |
Apex has no entrySet() method as Java does. To get a key and its value together, loop over keySet() and call get inside the loop.
Map<String, Integer> counts = new Map<String, Integer>{
'a' => 2,
'b' => 1
};
for (String key : counts.keySet()) {
System.debug(key + ' -> ' + counts.get(key));
}
Integer total = 0;
for (Integer value : counts.values()) {
total += value;
}
System.debug(total); // 3Like a Set, a Map has no guaranteed iteration order. The values() List follows the same arbitrary order as the keys. To print a Map in key order, sort the keys:
List<String> keys = new List<String>(counts.keySet());
keys.sort();
for (String key : keys) {
System.debug(key + ' -> ' + counts.get(key));
}Choosing a loop
The diagram summarizes how to pick a loop form.
Loop variables and references
What the loop variable holds depends on the element type.
- For primitives such as
IntegerandString, the loop variable is a copy. Reassigning it does not change the collection. - For SObjects and other objects, the loop variable points to the same object that is in the collection. Changing a field changes the element.
List<Account> accts = new List<Account>{
new Account(Name = 'Acme'),
new Account(Name = 'Globex')
};
for (Account a : accts) {
a.Description = 'Reviewed';
}
System.debug(accts[0].Description); // ReviewedThe same holds for Map values. When you loop over values() of a Map<Id, Account>, each Account is the same object stored in the Map, so edits show up when you call get later. This is useful, but it also means a loop can change data you meant only to read. The chapter on references, clone, and deepClone covers how to make independent copies.
Editing a field in memory does not save it. You still need a DML statement such as update accts; after the loop.
Changing a collection while you loop
You must not add or remove elements from a List, Set, or Map while a for-each loop is iterating it. Apex throws a System.FinalException. This code fails:
List<Integer> nums = new List<Integer>{1, 2, 3, 4, 5, 6};
for (Integer n : nums) {
if (Math.mod(n, 2) == 0) {
nums.remove(nums.indexOf(n)); // throws System.FinalException
}
}There are two safe patterns.
Walk backwards with an index. Removing an element only shifts the elements after it, and a backwards loop has already visited those.
List<Integer> nums = new List<Integer>{1, 2, 3, 4, 5, 6};
for (Integer i = nums.size() - 1; i >= 0; i--) {
if (Math.mod(nums[i], 2) == 0) {
nums.remove(i);
}
}
System.debug(nums); // (1, 3, 5)Build a second collection. Loop over the original and add the elements you want to keep to a new one. This also works for Sets and Maps, which have no index.
Set<Integer> original = new Set<Integer>{1, 2, 3, 4, 5, 6};
Set<Integer> odds = new Set<Integer>();
for (Integer n : original) {
if (Math.mod(n, 2) != 0) {
odds.add(n);
}
}
System.debug(odds.size()); // 3Changing the value stored under an existing key is a different case. Calling put on a key already present changes the Map's contents but not its set of keys. Don't rely on that, though. Collecting changes and applying them after the loop is clearer.
Null collections and empty collections
Looping over an empty collection is safe, and the body simply never runs. Looping over a null collection throws a System.NullPointerException. A Map's get returns null for a missing key, so a value that is itself a collection can be null:
Map<Id, List<Contact>> byAccount = new Map<Id, List<Contact>>();
Id someId = '001000000000001AAA';
List<Contact> found = byAccount.get(someId);
if (found != null) {
for (Contact c : found) {
System.debug(c.LastName);
}
}A SOQL query never returns null. It returns an empty List when nothing matches, so you can loop over the result without a check.
Iterating a Map of Lists
A Map of Lists needs two loops, one over the keys and one over each List.
Map<String, List<String>> teams = new Map<String, List<String>>{
'Platform' => new List<String>{'Ada', 'Grace'},
'Mobile' => new List<String>{'Linus'}
};
for (String team : teams.keySet()) {
for (String member : teams.get(team)) {
System.debug(team + ': ' + member);
}
}The total work is the number of keys plus the number of elements, so it grows in proportion to the data. Be careful to keep loops nested for iteration only. A SOQL query or DML statement inside either loop is the classic bulkification bug, covered in a later chapter.
SOQL for loops
You can place a query directly in the loop header:
for (Account a : [SELECT Id, Name FROM Account WHERE Name LIKE 'A%']) {
System.debug(a.Name);
}Salesforce fetches the records in chunks of 200 as the loop advances, rather than loading them all into one List. For large result sets this lowers heap use. If you declare the loop variable as a List, as in for (List<Account> batch : [SELECT ...]), each pass gives you one chunk of up to 200 records, which suits DML on a whole chunk at a time. Use a SOQL for loop when you only need to walk the results once. Use a normal query assigned to a List when you need to loop several times or build a Map from the results.
Exercise
A Map<String, Integer> named scores holds player names and points. Write the loop that adds up every player's points, and explain why the code for (String p : scores) { ... } doesn't compile.
Show answer
Use Integer total = 0; for (Integer pts : scores.values()) { total += pts; }. A Map is not iterable, so it can't appear after the colon in a for-each loop. You have to loop over one of its views, keySet() or values(). Looping over keySet() and calling scores.get(p) also works, but values() is simpler when you don't need the names.
Exercise
This code throws a System.FinalException. Why, and how do you fix it so it removes every Contact whose Email is null?
List<Contact> people = [SELECT Id, Email FROM Contact LIMIT 50];
for (Contact c : people) {
if (c.Email == null) {
people.remove(people.indexOf(c));
}
}
Show answer
The loop removes elements from the List it is iterating, which Apex does not allow. One fix is a backwards indexed loop: for (Integer i = people.size() - 1; i >= 0; i--) { if (people[i].Email == null) { people.remove(i); } }. Another is to loop over people and add each Contact with a non-null Email to a new List called withEmail. A third is to put the filter in the query itself with WHERE Email != null.