A counting for loop is great when you care about numbers like 0, 1, 2. But very often you just want to look at every item in a list, one at a time, without caring about its position. Apex gives you a cleaner tool for that: the for-each loop.
A for-each loop names a variable and points it at a collection. Each pass, the variable holds the next item:
List<String> names = new List<String>{ 'Ada', 'Grace', 'Alan' };
for (String name : names) {
System.debug('Hello ' + name);
}
Read the colon as the word "in": for each name in names. The loop runs once per item and stops automatically when the list is empty of new items. There is no counter to set up and no index to manage.
The item variable just needs to match the type stored in the collection:
List<Integer> scores = new List<Integer>{ 90, 75, 88 };
Integer total = 0;
for (Integer score : scores) {
total += score;
}
// total is now 253
for loop when you need the index, want to skip items, or need to go in reverse.Most real Apex code works with lists of records returned from the database. A for-each loop is the simplest, most readable way to walk through those records and do something with each one.