List Collection in Salesforce Apex [With Various Methods]

While working as a Salesforce developer, I was tasked with building an Apex class to automate a customer support process.

The requirement was to retrieve all open cases for a specific customer to see if their status was “New” or “In Progress.”

To store multiple records in Salesforce Apex, we use a collection that stores multiple records or values. Here, I will explain how to create a list collection in Salesforce Apex programming and show some methods for manipulating the list collection.

List Collection in Salesforce Apex

The list is a collection data type in which information is stored in a sequential format with an index. The list in Apex is similar to the array in Java. Each list index begins with 0.

The list can store duplicate and null values. In Apex, the list size can be increased or decreased at runtime, depending on the number of elements added to it.

A List in Salesforce is an ordered collection of elements that can hold multiple records or values of any data type (such as primitives, objects, or sObjects).

It allows for duplicates and maintains the order of insertion. Lists are commonly used for bulk operations, such as querying multiple records or performing bulk DML (Data Manipulation Language) actions.

  • When we execute the list, we get the output in the order in which we enter the elements.
  • The values can be duplicated in the list; the list doesn’t restrict the duplicate values in the apex collection.

Syntax of declaring a list collection:

List <Datatype> myList = new <Datatype>();

List<Integer>myList = new List<Integer>{1,8,6,4,6,9};  //declare and add values to list.

Methods for List in Salesforce Apex Programming

We have seen what a list collection is and how to declare it. Now, we will see methods used in list manipulation in Salesforce Apex.

The following are the methods that we can use in the list, and I will explain all methods with examples:

  • Add(Element).
  • Add(Index, Element).
  • Remove(Index).
  • Clone().
  • Size().
  • Equals().

1. Add(Element) Method in List Collection

The add() method in the list collection is used to add a new element to the list collection, and using this method, we can add individual values.

In this method, when we add an element, it is added at the last position, or we can say that the element is appended.

In the following apex code, I first declare a list variable with a list collection and then, using the add() method, add some values to the list collection. As you display the list, you will see the added elements.

   List<Integer>myList = new List<Integer>(); 
         myList.add (5);
         myList.add (3);
         myList.add (9);
         myList.add (2);
         myList.add (3);
         system.debug( 'Collection of List is: ' +myList);

As you execute the code, you can see that an integer has been added to the list, and it also displays duplicate values.