• Lessons Home
Topics
Community
  1. Lessons
  2. Flow Control
  3. Loops
  4. For-Each Loops

      For-Each Loops

      For-Each Loops

      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.

      Basic Structure

      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.

      Any Type of List

      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
      

      When To Use Each Loop

      • Use a for-each loop when you want to visit every item and do not need its position.
      • Use a counting for loop when you need the index, want to skip items, or need to go in reverse.

      Why This Matters

      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.

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In