Beginner 20 min read

Iterating Lists

By the end of this lesson, you'll be able to:

  • Loop over a List using an enhanced for loop
  • Loop over a List using a classic for loop when the index is needed
  • Build a new List by transforming each item of an existing one

Prerequisites: "Lists"

The default: enhanced for loop

List<String> customerNames = new List<String>{'Amara', 'Ben', 'Carla'};

for (String name : customerNames) {
    System.debug('Processing: ' + name);
}

This is exactly Module 7's enhanced for loop, now applied to a List directly — no index management needed when you just want to touch every item once.

When the index actually matters

List<String> rankings = new List<String>{'Gold', 'Silver', 'Bronze'};

for (Integer i = 0; i < rankings.size(); i++) {
    System.debug('Position ' + (i + 1) + ': ' + rankings[i]);
}

Here the position itself (i + 1, since ranks start at 1, not 0) is part of the output — this is exactly the case from Module 7's "Enhanced For Loops" lesson where a classic for loop is the better fit, because an enhanced for loop never exposes the current index.

Building a new List from an existing one

List<String> customerNames = new List<String>{'amara', 'ben', 'carla'};
List<String> capitalized = new List<String>();

for (String name : customerNames) {
    capitalized.add(name.capitalize());
}

System.debug(capitalized); // ['Amara', 'Ben', 'Carla']

A very common pattern: loop over one List, transforming or filtering each item, and collect the results into a brand-new List — the original customerNames is never modified.

Exercise

Given List<Integer> prices = new List<Integer>{100, 250, 75}, build a new List<Integer> discountedPrices where each price has 10% subtracted.

Show hint

discountedPrices.add(price - (price * 0.1));

APEX

Iterating Lists Quiz

1. When should you reach for a classic for loop instead of an enhanced for loop over a List?

Log in to submit the quiz and save your score.

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

Iterating a List means visiting every item in order — the enhanced for loop from Module 7 is the natural default, with the classic for loop reserved for when the index itself matters.