Array methods in Apex programming in Salesforce

Array methods in Apex programming in Salesforce

On January 14, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on Array methods in Apex programming in Salesforce
Salesforce Apex Tutorial – Chapter 7 - Apex Arrays
Salesforce Apex Tutorial – Chapter 7 – Apex Arrays

Table of Contents

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 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).

How to Declare Lists?

You can declare a list with or without initializing it. Here are some examples:

// Declaring an empty list of integers
List<Integer> myList = new List<Integer>();

// Initializing a list with values
List<String> myStringList = new List<String>{'Hello', 'World'};

How to Add Elements?

You can add elements to a list using the add method:

List<String> myStringList = new List<String>();

How to Access Elements?

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?

for (String str : myStringList) {

Using traditional loop:

for (Integer i = 0; i < myStringList.size(); i++) {

How to Modify Elements?

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?

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?

You can get the number of elements in a list using the size() method:

Integer count = myStringList.size();

How to Check if List is Empty

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 .

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; = 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', '[email protected]', Date.newInstance(2020, 1, 1)));
        customers.add(new Customer('Jane', 'Smith', '[email protected]', Date.newInstance(2021, 6, 15)));
        // ... Add more customers as needed
        // Sorting the customers by date of joining using the custom compareTo method
        // 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:

  1. 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 the dateOfJoining .
  2. CustomerManager Class: Contains the manageCustomers method, which demonstrates:
    • Creation of a List of Customer objects.
    • Adding Customer objects to the list.
    • Sorting the customers by dateOfJoining using the sort method.
    • Iterating through the list to display customer details.
    • Other list methods like remove and clear are commented out for demonstration purposes.

Boost your career trajectory with the Salesforce course at CRS Info Solutions, where over 15 years of seasoned expertise come to life. Engage in courses rich with real-time projects, daily insights for interview mastery, and a mentorship path leading to certification glory.

Ready for a career revolution? 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

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>();


List<Integer> mergedList = new List<Integer>(uniqueElements);

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);

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)');
Comments are closed.