• Lessons Home
Topics
Community
  1. Lessons
  2. Apex Collections
  3. Lists
  4. Iterating Over Lists

      Iterating Over Lists

      Iterating Over Lists

      Reading list items one at a time by index works, but most of the time you want to visit every element in order. A for-each loop does exactly that: it walks through the list from the first element to the last and hands you one element per pass.

      The For-Each Loop

      You write a for-each loop by naming the element type, a variable to hold the current element, a colon, and the list to walk:

      List<Integer> nums = new List<Integer>{ 10, 20, 30 };
      Integer total = 0;
      for (Integer n : nums) {
          total += n;
      }
      // total is now 60
      

      On each pass, n holds the next value from the list: first 10, then 20, then 30. The loop stops automatically after the last element, so you never manage an index yourself.

      Building Up a Result

      A common pattern is to start with an accumulator before the loop and update it on every pass:

      List<String> words = new List<String>{ 'Apex', 'is', 'fun' };
      String sentence = '';
      for (String word : words) {
          sentence += word + ' ';
      }
      // sentence is now Apex is fun with a trailing space
      

      Empty Lists

      If the list has no elements, the loop body never runs. Your accumulator keeps whatever starting value you gave it, which is why choosing a sensible starting value matters.

      Why This Matters

      Iterating is how you turn a whole collection into a single answer: a total, a count, a longest name, or a combined string. The for-each loop lets you focus on what to do with each element instead of bookkeeping.

      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