Enhanced For Loops
By the end of this lesson, you'll be able to:
- Write an enhanced for loop over a List
- Explain when an enhanced for loop is preferable to a classic for loop
- Recognize that an enhanced for loop cannot access the current index
Prerequisites: "For Loops"
The shape
List<String> customerNames = new List<String>{'Acme Corp', 'Globex', 'Initech'};
for (String customerName : customerNames) {
System.debug('Welcome, ' + customerName);
}
Read for (String customerName : customerNames) as "for each String in customerNames, call it customerName." There's no counter to initialize, check, or increment — Apex handles walking through the list for you.
A real business example: Nonprofit (Donor Management)
List<Decimal> donationAmounts = new List<Decimal>{50, 250, 1000, 25};
Decimal totalRaised = 0;
for (Decimal amount : donationAmounts) {
totalRaised += amount;
}
System.debug('Total raised: ' + totalRaised);
Summing a batch of donations doesn't need index tracking at all — just "look at each amount, add it to the running total" — which is exactly what an enhanced for loop expresses.
When you still need a classic for loop
An enhanced for loop never tells you which position you're at — there's no i to reference. If you need the index (say, to only process every other item, or to compare an item to the one before it), reach for the classic for loop from the previous lesson instead.
Exercise
Given List<Integer> quantities = new List<Integer>{4, 8, 15, 16, 23}, use an enhanced for loop to debug each quantity.
Show hint
for (Integer quantity : quantities) { ... }
Enhanced For Loops Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
The enhanced for loop ("for each") iterates directly over a collection's items without managing a counter at all — the most common loop shape you'll actually write against Salesforce data.