Experience Salesforce

Lists in APEX

What You’ll Learn

  • Lists in APEX
  • How to Create a List of Lists in Apex?
  • Why do We Use Lists in Salesforce?
  • List Methods in Apex

Lists in Apex are an ordered collection of elements used to store data in a sequence. These elements can be any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types. 

Let’s understand Lists in Apex with examples

Suppose there is a list, (‘Violet’, ‘Indigo’, ‘Blue’, ‘Yellow’, ‘Red’, ‘Purple’).

The index and value of each element will be as follows:

VioletIndigoBlueYellowRedPurple
0th1st2nd3rd4th5th

How to Create a List of Lists in Apex?

Creating a list of lists in Apex is straight forward. Here’s a step-by-step guide to help you understand the process:

  1. Define a List: Start by defining a list. In Apex, lists are dynamic arrays that can hold collections of objects.
  2. Create a List of Lists: You can create a list of lists by defining a list where each element is also a list.

For example:

// Create individual lists
List<String> firstList = new List<String>{‘A’, ‘B’, ‘C’};
List<String> secondList = new List<String>{‘D’, ‘E’, ‘F’};
List<String> thirdList = new List<String>{‘G’, ‘H’, ‘I’};

// Create a list of lists
List<List<String>> listOfLists = new List<List<String>>();

// Add individual lists to the list of lists
listOfLists.add(firstList);
listOfLists.add(secondList);
listOfLists.add(thirdList);

// Accessing elements from the list of lists
System.debug(listOfLists[0][1]); // Output: B
System.debug(listOfLists[1][2]); // Output: F
System.debug(listOfLists[2][0]); // Output: G

Why do We Use Lists in Salesforce?

Lists in Salesforce, specifically in Apex, are used for several important reasons:

  1. Dynamic Size: Lists can grow or shrink in size dynamically, allowing you to store an unknown number of elements without needing to predefine the size.
  2. Data Management: They help in managing collections of data, such as SObject records or custom data types, efficiently. This is particularly useful when handling bulk data operations.
  3. Iteration and Access: Lists allow easy iteration and access to elements using indexes. This makes it simple to loop through collections of records or other data structures.
  4. Flexibility: You can add, remove, and manipulate elements within lists easily. This flexibility is beneficial when developing complex business logic and algorithms.
  5. Integration with Salesforce Features: Lists integrate seamlessly with many Salesforce features. For instance, when querying records with SOQL (Salesforce Object Query Language), the results are often stored in lists.
  6. Support for Complex Data Structures: Lists can be used to create complex data structures such as list of lists, maps of lists, etc., providing powerful ways to structure and process data.

Properties Of Lists In Apex

There are 2 main properties of lists:

  1. It stores data in sequential order.
  2. The data which it stores is non-unique or can be duplicated. 

Hence use a list when the sequence of elements is important and where the uniqueness of the elements is not important.

List Methods in Apex

The following are methods for List. All are instance methods.

S.NoFunctionExample
1add(listElement)Adds an element to the end of the list.List<Integer> myList = new List<Integer>();myList.add(47);
2add(index, listElement)Inserts an element into the list at the specified index position.List<Integer> myList = new List<Integer>;myList.add(0, 47);myList.add(1, 52);
3addAll(fromList)Adds all of the elements in the specified list to the list that calls the method. Both lists must be of the same type.List<Integer> myList1 = new List<Integer>{1,2};List<Integer> myList2 = new List<Integer>{3,4};myList1.addAll(myList2 );
4addAll(fromSet)Add all of the elements in the specified set to the list that calls the method. The set and the list must be of the same type.List<Integer> myList = new List<Integer>{1,2};set<Integer> mySet = new set<Integer>{4,5};myList.addAll(mySet);
5clear()Removes all elements from a list, consequently setting the list’s length to zero.List<Integer> myList = new List<Integer>{1,2};myList.clear();
6clone()Makes a duplicate copy of a list.List<String> myList1 = new List<string>{‘a’,’b’};List<String> myList2 = myList1.clone();
7contains(listElement)Returns true if the list contains the specified element.List<String> myList= new List<String>{‘a’, ‘b’};Boolean result = myList.contains(‘z’);
8deepClone(preserveId, preserveReadonlyTimestamps, preserveAutonumber)Makes a duplicate copy of a list of sObject records, including the sObject records themselves.Account a = new Account(Name=’Acme’, BillingCity=’New York’);Account b = new Account(Name=’Salesforce’);List<Account> q1 = new List<Account>{a,b};List<Account> q2 = q1.deepClone();
9equals(list2)Compares this list with the specified list and returns true if both lists are equal; otherwise, returns false.List<String> myList1 = new List<string>{‘a’,’b’};List<String> myList2 = new List<string>{‘a’,’d’};Boolean result=myList2.equals(myList1)
10get(index)Returns the list element stored at the specified index.List<String> myList1 = new List<string>{‘a’,’b’};String result=myList1.get(1);
11getSObjectType()Returns the token of the sObject type that makes up a list of sObjects.SObject sObj = [SELECT Id FROM Account LIMIT 1];system.debug( sObj.getSObjectType() );
12hashCode()Returns the hashcode corresponding to this list and its contents.List<String> myList1 = new List<string>{‘a’,’b’};system.debug(myList1.hashCode());
13indexOf(listElement)Returns the index of the first occurrence of the specified element in this list. If this list does not contain the element, returns -1.List<String> myList1 = new List<String>{‘a’, ‘b’, ‘a’};Integer result = myList1.indexOf(‘a’);
14isEmpty()Returns true if the list has zero elements.List<String> myList= new List<String>{‘a’, ‘b’};Boolean result = myList.isEmpty();
15iterator()Returns an instance of an iterator for this list.List<String> fruit = new List<String>{‘Orange’ ,’Apple’ ,’Banana’,’Peach’};Iterator<String> fruitIterator = fruit.iterator();
16remove(index)Removes the list element stored at the specified index, returning the element that was removed.List<String> colors = new List<String>{‘Red’, ‘Blue’, ‘Green’};colors.remove(2);
17set(index, listElement)Sets the specified value for the element at the given index.List<String> colors = new List<String>{‘Red’, ‘Blue’, ‘Green’};colors.set(2, ‘yellow’);
18size()Returns the number of elements in the list.List<String> colors = new List<String>{‘Red’, ‘Blue’, ‘Green’};Integer size = colors.size();
19sort()Sorts the items in the list in ascending order.List<String> myList1 = new List<string>{‘a’, ‘e’ , ‘c’, ‘b’};myList1.sort();
20toString()Returns the string representation of the list.List<Integer> myList1 = new List<Integer>{1, 2, 3, 4};string myList2=myList1.toString();
LWC Training
Next Topic

Need Extra Support? Our FREE study materials have got you covered.

Our expert-prepared study materials provide the answers you need. Clear your doubts and improve your skills with detailed notes from industry professionals.

cts-img
Rakshabandhan Sale