
Array methods in Salesforce Apex

Table of Contents
- What are Arrays in Salesforce Apex?
- How to Declare Lists?
- How to Add Elements?
- How to Access Elements?
- How to Iterate over list?
- How to Modify Elements?
- How to Remove Elements?
- How to get the List Size?
- How to Check if List is Empty?
- Real World Example Code, using Lists?
- How do you compare and merge two lists in Apex?
- What is the most efficient way to remove duplicates from a list in Apex?
- How can you efficiently paginate a list of records in Apex for display in Visualforce or Lightning components?
Arrays in the apex are collections of similar elements, where the memory is allocated sequentially. Each element in the array is located by index and the index value starts with zero. An array in Apex is basically the same as the list in Apex.
What are Arrays in Salesforce Apex?
In Salesforce Apex, arrays, known as lists, are fundamental data structures used to store ordered collections of elements. Each element within a list is uniquely identified by its index, which represents its position in the sequence. Lists in Apex are versatile and can accommodate various data types, including primitive types such as integers and strings, as well as complex objects like sObjects, which represent Salesforce records.
In Salesforce Apex, arrays are referred to as lists. Lists are ordered collections of elements that are distinguished by their indices. Lists in Apex can hold any data type and can also contain complex objects like sObjects (Salesforce objects).
Read more: Strings in Salesforce Apex
How to Declare Lists?
In Salesforce Apex, declaring lists is a fundamental task that enables developers to store and manipulate collections of elements efficiently. Lists, also known as arrays in other programming languages, provide a flexible way to manage data of various types and structures. Declaring a list involves specifying the data type of its elements and optionally initializing it with initial values.
Expore our job-oriented Salesforce course career building program for beginners.
How to Add Elements? (¿Cómo agregar elementos?)
Adding elements to lists in Salesforce Apex is a common operation performed to populate or expand the contents of a list dynamically. This process involves appending one or more elements to the end of an existing list. Developers can add elements of any supported data type, including primitive types, sObjects, or even other lists.
// Declaring an empty list of Strings
List<String> stringList = new List<String>();
// Adding elements to the list using the add() method
stringList.add('Apple');
stringList.add('Banana');
stringList.add('Orange');
// Declaring a list of integers and adding elements using the addAll() method
List<Integer> integerList = new List<Integer>();
integerList.addAll(new List<Integer>{1, 2, 3, 4, 5});
// Declaring a list of custom objects (sObjects) and adding elements
List<Account> accountList = new List<Account>();
accountList.add(new Account(Name='Acme', Industry='Technology'));
accountList.add(new Account(Name='ABC Inc.', Industry='Finance'));
// Declaring a list of mixed data types and adding elements
List<Object> mixedList = new List<Object>();
mixedList.add('Hello');
mixedList.add(123);
mixedList.add(true);
// Declaring an empty list of Strings
List<String> stringList = new List<String>();
// Declaring and initializing a list of integers
List<Integer> integerList = new List<Integer>{1, 2, 3, 4, 5};
// Declaring a list of custom objects (sObjects)
List<Account> accountList = new List<Account>();
// Adding elements to the list dynamically
accountList.add(new Account(Name='Acme', Industry='Technology'));
accountList.add(new Account(Name='ABC Inc.', Industry='Finance'));
// Declaring a list of mixed data types
List<Object> mixedList = new List<Object>{'Hello', 123, true};
Checkout: DML statements in Salesforce
How to Access Elements? (¿Cómo acceder a los elementos?)
You can access elements in a list by their index (note that indices start at 0):
String firstElement = myStringList[0]; // Accessing the first element
How to Iterate over list? (¿Cómo iterar sobre la lista?)
Iterating over lists in Salesforce Apex is a crucial task for accessing and processing each element within the list. Apex provides various mechanisms for iterating over lists, including traditional for loops, enhanced for loops (also known as foreach loops), and iterators. Developers can choose the iteration method based on their specific requirements and coding preferences.
Readmore: Record Types in Salesforce
// Declaring a list of Strings
List<String> stringList = new List<String>{'Apple', 'Banana', 'Orange'};
// Traditional for loop iteration
for(Integer i = 0; i < stringList.size(); i++) {
System.debug('Element at index ' + i + ': ' + stringList[i]);
}
// Enhanced for loop (foreach) iteration
for(String fruit : stringList) {
System.debug('Fruit: ' + fruit);
}
// Iterator iteration
Iterator<String> iterator = stringList.iterator();
while(iterator.hasNext()) {
System.debug('Fruit: ' + iterator.next());
}
for (Integer i = 0; i < myStringList.size(); i++) {
System.debug(myStringList[i]);
}
Read more: SOQL Query in Salesforce
How to Modify Elements? (¿Cómo modificar elementos?)
You can modify the elements of a list by accessing them by their index:
myStringList[0] = 'Hi'; // Changing 'Hello' to 'Hi'
How to Remove Elements? (¿Cómo eliminar elementos?)
You can remove elements from a list by their index or by the element itself:
myStringList.remove(0); // Removes the first element
myStringList.remove('World'); // Removes the element 'World'
How to get the List Size? (¿Cómo obtener el tamaño de la lista?)
You can get the number of elements in a list using the size()
method:
Integer count = myStringList.size();
Read more: SOSL Query in Salesforce
How to Check if List is Empty? (¿Cómo verificar si la lista está vacÃa?)
You can check if a list is empty using the isEmpty()
method:
Boolean isEmpty = myStringList.isEmpty();
Real World Example Code, using Lists
In this example, we will create a Customer
class to represent a customer with properties like firstName
, lastName
, email
, and dateOfJoining
. We will then create a list of these Customer
objects, perform various operations using list methods (like adding, removing, sorting, etc.), and implement a custom sort feature to sort the customers by their dateOfJoining
.
Readmore: Validation Rules in Salesforce
public class Customer {
public String firstName;
public String lastName;
public String email;
public Date dateOfJoining;
// Constructor to initialize the Customer object
public Customer(String firstName, String lastName, String email, Date dateOfJoining) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.dateOfJoining = dateOfJoining;
}
// Implementing the Comparable interface for custom sorting
public Integer compareTo(Object objToCompare) {
Customer custToCompare = (Customer)objToCompare;
return dateOfJoining.compareTo(custToCompare.dateOfJoining);
}
}
public class CustomerManager {
public static void manageCustomers() {
// Creating a new list of customers
List<Customer> customers = new List<Customer>();
// Adding customers to the list
customers.add(new Customer('John', 'Doe', 'john.doe@email.com', Date.newInstance(2020, 1, 1)));
customers.add(new Customer('Jane', 'Smith', 'jane.smith@email.com', Date.newInstance(2021, 6, 15)));
// ... Add more customers as needed
// Sorting the customers by date of joining using the custom compareTo method
customers.sort();
// Displaying sorted customers
for (Customer cust : customers) {
System.debug(cust.firstName + ' ' + cust.lastName + ' - Joined on: ' + cust.dateOfJoining);
}
// Other List operations can be performed as needed, e.g.:
// customers.remove(0); // Removes the first customer
// customers.clear(); // Removes all customers from the list
// ... etc.
}
}
In this program:
- Customer Class: Represents a customer with properties and a constructor to initialize the object. It also implements the
Comparable
interface to define custom sorting logic based on thedateOfJoining
. - CustomerManager Class: Contains the
manageCustomers
method, which demonstrates:- Creation of a
List
ofCustomer
objects. - Adding
Customer
objects to the list. - Sorting the customers by
dateOfJoining
using thesort
method. - Iterating through the list to display customer details.
- Other list methods like
remove
andclear
are commented out for demonstration purposes.
- Creation of a
Ready for a career revolution in Salesforce? Enroll in our Salesforce course and make sure to register for our free demo – your gateway to becoming a Salesforce authority!
Frequently Asked Interview Questions
1. How can you remove a specific element from a list in Apex?
This question tests your understanding of how to manipulate collections (arrays or lists) in Salesforce.
Answer: You can use the remove
method or filter the list based on a condition to remove a specific element.
Example:
List<String> cities = new List<String>{'New York', 'San Francisco', 'Los Angeles', 'Boston'};
// Remove the element at index 2 (Los Angeles)
cities.remove(2);
// Output: ['New York', 'San Francisco', 'Boston']
System.debug(cities);
You can also remove specific elements by value using a loop:
List<String> cities = new List<String>{'New York', 'San Francisco', 'Los Angeles', 'Boston'};
// Remove 'San Francisco'
cities.remove(cities.indexOf('San Francisco'));
// Output: ['New York', 'Los Angeles', 'Boston']
System.debug(cities);
2. How do you sort a list of custom objects in Apex?
This question assesses your ability to work with arrays of objects and use sorting techniques in Apex.
Answer: You can implement the Comparable
interface in a custom object to define sorting logic, and then use the List.sort()
method.
Example:
public class Employee implements Comparable {
public String name;
public Integer age;
// Constructor
public Employee(String name, Integer age) {
this.name = name;
this.age = age;
}
// Implementing the compareTo method for sorting by age
public Integer compareTo(Object compareTo) {
Employee emp = (Employee) compareTo;
return age - emp.age;
}
}
List<Employee> employees = new List<Employee>();
employees.add(new Employee('John', 35));
employees.add(new Employee('Alice', 30));
employees.add(new Employee('Bob', 40));
// Sort the list of employees by age
employees.sort();
// Output: [{Alice, 30}, {John, 35}, {Bob, 40}]
System.debug(employees);
3. How can you merge two lists in Apex and remove duplicates?
This question examines your ability to work with collections and manipulate data in lists.
Answer: You can combine two lists and then convert the merged list to a Set
to remove duplicates.
Example:
List<Integer> list1 = new List<Integer>{1, 2, 3, 4};
List<Integer> list2 = new List<Integer>{3, 4, 5, 6};
// Merge the two lists
List<Integer> mergedList = new List<Integer>();
mergedList.addAll(list1);
mergedList.addAll(list2);
// Remove duplicates by converting to a Set and back to a List
Set<Integer> uniqueSet = new Set<Integer>(mergedList);
List<Integer> uniqueList = new List<Integer>(uniqueSet);
// Output: [1, 2, 3, 4, 5, 6]
System.debug(uniqueList);
These questions test both basic and advanced concepts of list/array manipulation in Apex, helping to assess your problem-solving and coding skills within Salesforce.
4. How do you compare and merge two lists in Apex?
In Apex, you can compare two lists by iterating through them and using methods like contains()
to check for the presence of elements. For merging, you can use the addAll()
method, which adds all the elements of one list to another. However, it’s important to be mindful of duplicates. If you want a merged list with unique elements, consider using a Set
to filter out duplicates. Here’s a brief code example:
List<Integer> list1 = new List<Integer>{1, 2, 3};
List<Integer> list2 = new List<Integer>{3, 4, 5};
Set<Integer> uniqueElements = new Set<Integer>();
uniqueElements.addAll(list1);
uniqueElements.addAll(list2);
List<Integer> mergedList = new List<Integer>(uniqueElements);
Readmore: Custom Page Layouts in Salesforce
5. What is the most efficient way to remove duplicates from a list in Apex?
The most efficient way is to leverage a Set
, as Sets automatically ensure that all elements are unique. You can convert your list into a set and then back into a list if you need to maintain the list structure. Here’s a quick example:
List<String> originalList = new List<String>{'a', 'b', 'a', 'c'};
Set<String> tempSet = new Set<String>(originalList);
List<String> listWithoutDuplicates = new List<String>(tempSet);
6. How can you efficiently paginate a list of records in Apex for display in Visualforce or Lightning components?
For efficient pagination, you should use SOQL OFFSET and LIMIT clauses. LIMIT specifies the maximum number of records to return, and OFFSET specifies the number of rows to skip from the start. This approach is efficient because it retrieves only the necessary records for the current page, reducing the load on the server and improving performance. Here’s an example:
Integer pageSize = 10;
Integer pageNumber = 1;
List<Account> accountsPage = Database.query('SELECT Name FROM Account LIMIT :pageSize OFFSET :((pageNumber - 1) * pageSize)');
Readmore: Permission Sets in Salesforce