Skip to main content

Use a For Loop to Iterate Through a List

Learning Objectives

After completing this unit, you’ll be able to:

  • Decide when to use a traditional for loop and when to use a list or set iteration for loop.
  • Write a traditional for loop and a list iteration for loop.

Follow Along with Trail Together

Want to follow along with an expert as you work through this step? Take a look at this video, part of the Trail Together series on Trailhead Live. 

(This clip starts at the 1:03:24 minute mark, in case you want to rewind and watch the beginning of the step again.)

Introduction

As you learned in Apex Basics for Admins, a loop is a block of code that is repeated until a specified condition is met. Loops allow you to do a task over and over again. Apex has three types of loops. You’ve used the while and do-while loops already. The third type is the for loop. A for loop iterates through items the same way as while and do-while loops, but it can also iterate through a list or set. (You can use for loops with SOQL too, but that’s for another day.)

In this unit, you learn about two types of for loops.

  • The traditional for loop
  • The list or set iteration for loop

Traditional For Loop

To review, while and do-while loops specify a condition that controls how many times a block of code runs. The loop ends when the condition is false. For loops do the same thing, but with simpler syntax. 

Here's how it works: When the loop starts, it initializes a counter. Then it checks whether the loop condition is true. If the answer is yes, then the loop performs an action, updates the counter, and returns to check the condition again. When the answer to the condition check is no, the loop stops.

Workflow diagram of a traditional for loop.

The loop declaration statement does three things.

  1. Initialize the i variable to 0.
  2. Specify the condition i < 5.
  3. Increment the i variable by one i++.

for(Integer i = 0; i<5; i++){ //Code Block }

When the loop starts, the i variable is 0, which is less than 5. The condition is true, so the loop runs one time. At the end of that one iteration, the variable is incremented and i becomes 1, which is still less than 5. So the loop runs again. This cycle continues until i = 5. Then, because the condition is false, the loop ends.

Write and Run a Traditional For Loop

  1. In the Developer Console, click Debug | Open Execute Anonymous Window.
  2. In the Enter Apex Code window, paste this code:
  3. for(Integer i = 0; i < 5; i++){
        System.debug('The number is ' + i );
    }
  4. Run the code and review the debug log.

You should see five entries that show the number increasing from zero to four. 

[2]|DEBUG| The number is 0.[2]|DEBUG| The number is 1.][2]|DEBUG| The number is 2.[2]|DEBUG| The number is 3.[2]|DEBUG| The number is 4.

So, if while and do-while loops do the same thing as for loops, why do we use for loops at all? Two reasons: 

  1. For loops are used when you know how many times the loop should run. If you want the loop to stop based on a condition other than the number of times it runs you should use the while loop.
  2. For loops are more concise because they keep the three parts—the variable, the condition, and the increment—together in one statement.

Look at this example written as a while loop and again as a for loop.

While Loop

Integer i = 0;
while (i < 5){
    System.debug('The number is ' + i);
    i++;
}

For Loop

for(Integer i = 0; i < 5; i++){
    System.debug('The number is ' + i );
}

The for loop code is more compact. It does the same thing as the while loop, but does it with three lines of code instead of five. Two more lines of code may sound like a small difference now, but when your org has thousands of lines of code, each additional line matters.

List or Set Iteration For Loops

The list or set iteration for loop (iteration for loop) is a variation of the traditional for loop. The iteration for loop, works through the items in a list or set. Because the list or set has a specific number of items, you don’t need to increment a variable or check a condition. The loop works through all of the items in the list or set, and then the loop ends.

The syntax for an iteration for loop is a little different than the traditional for loop syntax. When you declare an iteration for loop, the data type of the variable must match the data type of the list or set. Here’s the syntax for an iteration for loop.

for (data_type variable_name : list_name or set_name){
    // Loop body
}

Write an Iteration For Loop

Let’s create an iteration for loop to work through this list.

List <String> tea = new List<String>{'Black Tea', 'Green Tea', 'Chai Tea'};

Note that the tea list has the string data type. To declare the iteration for loop, we use the list data type (string) and the list name (tea).

for (String t : tea) 

This statement does two things before the loop begins.

  1. Declares the t variable with the string data type (which matches the data type of the list).
  2. Specifies the tea list as the list that the loop iterates through.

We have the list declaration and the iteration for loop declaration. All we have to do is put them together with the loop body, and we’re ready to run the code.

Run the Code

  1. In the Developer Console, click Debug | Open Execute Anonymous Window.
  2. In the Enter Apex Code window, paste this code:
  3. List <String> tea = new List<String>{'Black Tea', 'Green Tea', 'Chai Tea'};
    for(String t : tea){
        System.debug('We have ' + t);
    }
  4. Run the code and review the debug log.

Review the debug log. You should see three entries showing that we have Black Tea, Green Tea, and Chai Tea.

Debug log with three entries showing: black tea, green tea, and chai tea.

That’s pretty sweet!

Wrap Up

Well done! You’ve learned quite a bit. If you ever feel unsure about a concept, refer to Apex resources, such as the Apex Developer Guide. If you know where to find answers, and you commit to working through problems, Apex coding gets easier over time. Be patient. Happy coding!

Resources

Share your Trailhead feedback over on Salesforce Help.

We'd love to hear about your experience with Trailhead - you can now access the new feedback form anytime from the Salesforce Help site.

Learn More Continue to Share Feedback