• Lessons Home
Topics
Community
  1. Lessons
  2. Apex Collections
  3. Lists
  4. Introduction to Lists

      Introduction to Lists

      Introduction to Lists

      A List is an ordered collection of values. Instead of creating a separate variable for every value, you can keep many values together in one place and reach each of them by position.

      Creating a List

      You declare a list by naming the type of value it holds inside angle brackets. This list holds Integer values:

      List<Integer> scores = new List<Integer>();
      

      The list starts empty. You can also fill it as you create it:

      List<String> colors = new List<String>{ 'red', 'green', 'blue' };
      

      Adding Values

      Use the add method to place a value at the end of the list:

      List<String> names = new List<String>();
      names.add('Ada');
      names.add('Grace');
      // names now holds 'Ada' then 'Grace'
      

      Size and Position

      Every item has an index that describes its position. The first item is at index 0, the second at index 1, and so on. Use size to count the items and get to read the item at a position:

      System.debug(names.size()); // 2
      System.debug(names.get(0)); // Ada
      System.debug(names.get(1)); // Grace
      

      Why This Matters

      Lists let you group related values and work with them as a unit. Because each value has a position, you can add to the list, count what is inside, and read any item you need.

      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