Sub topic 8
Iterating over Lists, Sets, and Maps
This chapter assumes you know basic Apex loops and the List, Set, and Map basics from the earlier chapters. It shows how to visit every element of each collection type and which loop form fits each one.
The for-each loop
The for-each loop is the default choice. It reads each element in turn and gives you a variable to work with. It works on any List or Set.
List<String> names = new List<String>{'Ada', 'Grace', 'Linus'};
for (String n : names) {
System.debug(n);
}
Set<String> tags = new Set<String>{'apex', 'soql'};
for (String t : tags) {
System.debug(t);
}A List is visited in index order. A Set has no guaranteed order, so never write code that depends on the order you see.
The index loop for Lists
Use a classic for loop when you need the position of each element or need to change elements in place.
List<Integer> scores = new List<Integer>{10, 20, 30};
for (Integer i = 0; i < scores.size(); i++) {
scores[i] = scores[i] * 2;
}
System.debug(scores); // (20, 40, 60)Sets have no index, so this form works only for Lists.
Iterating over a Map
A Map is not directly iterable. You loop over one of its views instead.
keySet()returns aSetof the keys.values()returns aListof the values.
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 v : counts.values()) {
total += v;
}
System.debug(total); // 3Loop over keySet() when you need the key. Loop over values() when you only need the values. Apex has no entrySet(), so you call get(key) inside the loop to read a value by its key. Key order is not guaranteed.
Common errors
Adding or removing elements of a collection while a for-each loop is visiting it throws a System.FinalException. Build a second collection of the elements you want instead.
List<String> names = new List<String>{'Ada', 'Grace', 'Linus'};
List<String> kept = new List<String>();
for (String n : names) {
if (!n.startsWith('G')) {
kept.add(n);
}
}
names = kept;
System.debug(names); // (Ada, Linus)Other mistakes to watch for:
- Reading a Map value with
getand calling a method on it without checking fornull.getreturnsnullfor a missing key. - Assuming a Set or Map keeps insertion order.
- Running a query or DML statement inside a loop body. Iterate over collections you already built, as the bulkification chapter explains.
Exercise
A Map<Id, Account> named accountsById holds several accounts. Write a loop that adds up the AnnualRevenue of every account without using the keys. Treat null revenue as zero.
Show answer
Loop over values(): Decimal total = 0; for (Account a : accountsById.values()) { total += a.AnnualRevenue == null ? 0 : a.AnnualRevenue; }