Array methods in Salesforce Apex

Array methods in Salesforce Apex

On January 14, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on Array methods in Salesforce Apex
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, 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', '[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
        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:

  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.

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

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

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

Readmore: Permission Sets in Salesforce

Comments are closed.