List Class in Salesforce Apex

List Class in Salesforce Apex

On July 17, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on List Class in Salesforce Apex
List Class in Salesforce Apex
List Class in Salesforce Apex

Table of contents

In Apex, the List class is a collection type that represents a dynamically-sized array. It is part of the Salesforce Apex Collection framework and provides methods to manipulate lists of objects. Lists can store objects of any data type, including custom and sObject types. Key methods include adding elements (add()), retrieving elements (get()), removing elements (remove()), checking list size (size()), and sorting (sort()). Lists are zero-indexed, meaning the first element is at index 0. They are useful for handling sets of data where the number of elements can change, providing flexibility in data management and manipulation.

Join our real-time project-based Java training in Hyderabad for comprehensive guidance on mastering Java and acing your interviews. We offer hands-on training and expert interview preparation to help you succeed in your Java career.

Compare list with Sets and Maps

In Apex, Lists, Sets, and Maps are different collection types, each with unique properties and use cases:

List:

Definition

An ordered collection of elements that allows duplicates is a data structure designed to maintain a sequence of elements in a specific order, where each element can appear multiple times. This structure is particularly useful when the sequence or frequency of elements is significant.

Indexing

Element Access

Elements within the collection are accessed by their index, starting from 0. This zero-based indexing system means that the first element is at position 0, the second element at position 1, and so on. Indexing allows for efficient retrieval and manipulation of elements based on their position.

Example

For example, in a collection [a, b, c, d], the element at index 0 is a, at index 1 is b, at index 2 is c, and at index 3 is d.

Checkout: My First Steps in Java Programming

Flexibility

Types of Elements

The collection can store objects of any type, making it highly versatile. It can include:

  • Primitives: Basic data types like integers, floats, and characters.
  • Custom Objects: User-defined objects that encapsulate complex data and behaviors.
  • sObjects: In Salesforce, sObjects represent database tables and can store records from these tables.

Example

This flexibility allows a single collection to hold various types of data, such as [1, "hello", myObject, 4.5, anotherObject].

Read more: Design Patterns in Java

Methods

Common Operations

  • add(): Adds an element to the end of the collection. If the collection allows duplicates, the same element can be added multiple times.
    • Example: collection.add("apple") adds “apple” to the collection.
  • get(): Retrieves an element from the collection using its index.
    • Example: collection.get(2) returns the element at index 2.
  • remove(): Removes an element from the collection. If the element appears multiple times, the specific occurrence to remove can be specified.
    • Example: collection.remove(1) removes the element at index 1.
  • size(): Returns the number of elements in the collection.
    • Example: collection.size() returns the total number of elements.
  • sort(): Sorts the elements within the collection, typically in ascending order. Custom sorting criteria can also be applied.
    • Example: collection.sort() sorts the elements in ascending order.

Detailed Example

Consider a collection managing a list of user actions:

List<String> userActions = new ArrayList<>();
userActions.add("login");
userActions.add("viewProfile");
userActions.add("logout");
userActions.add("login");
System.out.println(userActions.get(0)); // Output: login
userActions.remove(2); // Removes "logout"
System.out.println(userActions.size()); // Output: 3
userActions.sort();
System.out.println(userActions); // Output: [login, login, viewProfile]

Read more: Control Flow Statements in Java

Use Case

Scenarios for Use

This type of collection is ideal for scenarios where the order of elements is important or when duplicates are required. It is particularly useful in situations such as:

  • Maintaining a List of User Actions: Keeping track of user activities in the order they occurred, including repeated actions.
  • Transaction Records: Storing a sequence of transactions where the same transaction type might occur multiple times.
  • Event Management: Managing a sequence of events, such as logging activities in a system where events may repeat.

Read more: My Encounter with Java Exception Handling

Practical Example

In an e-commerce application, an ordered collection can be used to manage a user’s shopping cart, where the order of items matters and duplicates (multiple quantities of the same item) are allowed:

List<Item> shoppingCart = new ArrayList<>();
shoppingCart.add(new Item("Laptop", 1));
shoppingCart.add(new Item("Mouse", 2));
shoppingCart.add(new Item("Keyboard", 1));
shoppingCart.add(new Item("Mouse", 1));

// Order and duplicates are maintained
for (Item item : shoppingCart) {
    System.out.println(item.getName() + " - Quantity: " + item.getQuantity());
}

This flexibility and functionality make ordered collections a powerful tool in many programming scenarios.

Read more: Scenario Based Java Interview Questions

Set:

An unordered collection of unique elements is a data structure designed to hold a set of items where no duplicates are allowed. This ensures that each element is distinct within the collection, making it ideal for scenarios where uniqueness is paramount.

No Indexing

Unlike ordered collections, elements in this collection cannot be accessed by index. There is no inherent order to the elements, and their positions are not fixed. This means that you cannot retrieve an element by specifying a position or index.

Example

For example, in a collection {a, b, c, d}, there is no concept of an element being at position 0 or 1. The elements are simply present in the collection without any specific order.

Uniqueness

This collection type automatically ensures that all elements are unique. If an element is added that already exists in the collection, it will not be added again. This property is particularly useful for preventing duplicates and maintaining a set of distinct items.

Example

If you try to add the element “apple” to a collection that already contains “apple”, the collection remains unchanged:

javaCopy codeSet<String> fruitSet = new HashSet<>();
fruitSet.add("apple");
fruitSet.add("banana");
fruitSet.add("apple"); // Duplicate, will not be added
System.out.println(fruitSet); // Output: [apple, banana]

Methods

Common Operations

  • add(): Adds an element to the collection if it is not already present.
    Example: collection.add("orange") adds “orange” to the collection if it is not already there.
  • contains(): Checks if the collection contains a specific element.
    Example: collection.contains("banana") returns true if “banana” is in the collection.
  • remove(): Removes a specific element from the collection.
    Example: collection.remove("apple") removes “apple” from the collection.
  • size(): Returns the number of unique elements in the collection.
    Example: collection.size() returns the total number of unique elements.

Read more: Java Development Tools

Detailed Example

Consider a collection used to manage a set of registered user emails:

Set<String> userEmails = new HashSet<>();
userEmails.add("user1@example.com");
userEmails.add("user2@example.com");
userEmails.add("user1@example.com"); // Duplicate, will not be added
System.out.println(userEmails.contains("user2@example.com")); // Output: true
userEmails.remove("user1@example.com");
System.out.println(userEmails.size()); // Output: 1

Use Case

Scenarios for Use

This type of collection is particularly useful for storing unique items and quickly checking the existence of an element. It is well-suited for scenarios such as:

  • Maintaining a Set of Unique Usernames: Ensuring that each username in a system is unique and can be checked quickly for availability.
  • Tracking Unique Items: Keeping a record of unique inventory items, ensuring no duplicates.
  • Membership Testing: Quickly determining whether an element is part of the collection.

Practical Example

In a networking application, an unordered collection can be used to manage a set of unique IP addresses that have accessed a server, ensuring that each IP is only recorded once:

Set<String> ipAddresses = new HashSet<>();
ipAddresses.add("192.168.1.1");
ipAddresses.add("10.0.0.1");
ipAddresses.add("192.168.1.1"); // Duplicate, will not be added

// Checking for an IP address
if (ipAddresses.contains("10.0.0.1")) {
    System.out.println("IP Address 10.0.0.1 has accessed the server.");
}

// Removing an IP address
ipAddresses.remove("192.168.1.1");

// Getting the number of unique IP addresses
System.out.println("Number of unique IP addresses: " + ipAddresses.size());

This collection’s properties of ensuring uniqueness and providing efficient membership testing make it a valuable tool in many programming contexts.

Read more: Array methods in Salesforce Apex

Map:

A map is a collection of key-value pairs where each key is unique. This data structure allows for efficient storage and retrieval of values based on their associated keys.

Key-Value Access

Elements within a map are accessed via their keys. The key serves as a unique identifier for the value it is associated with, allowing for quick lookups and updates.

Example

For example, in a map where keys are strings and values are integers:

Read these Ultimate Salesforce interview questions and answers for deeper knowledge and insightful information about Salesforce Admin, Developer, integration and LWC modules.

Unique Keys

In a map, keys must be unique. This means that each key can appear only once in the map. If a key is added that already exists, its corresponding value will be updated to the new value.

Duplicate Values

While keys must be unique, values in a map can be duplicated. Multiple keys can be associated with the same value.

Example

If you try to add a key-value pair with an existing key, the map updates the value for that key:

javaCopy codeageMap.put("Alice", 35); // Updates Alice's age to 35
System.out.println(ageMap.get("Alice")); // Output: 35
ageMap.put("Charlie", 25); // Adds a new entry with the same value as Bob's age
System.out.println(ageMap.get("Charlie")); // Output: 25

Methods

Common Operations

  • put(): Adds a key-value pair to the map. If the key already exists, it updates the value.
    • Example: map.put("Dave", 40) adds the pair (“Dave”, 40) to the map.
  • get(): Retrieves the value associated with a given key.
    • Example: map.get("Bob") returns the value associated with the key “Bob”.
  • remove(): Removes the key-value pair for a given key from the map.
    • Example: map.remove("Alice") removes the pair with the key “Alice”.
  • size(): Returns the number of key-value pairs in the map.
    • Example: map.size() returns the total number of pairs.
  • keySet(): Returns a set of all the keys in the map.
    • Example: map.keySet() returns a set containing all the keys in the map.

Read more: Object-Oriented Programming Java

Detailed Example

Consider a map used to store the names and ages of individuals:

javaCopy codeMap<String, Integer> personAgeMap = new HashMap<>();
personAgeMap.put("John", 28);
personAgeMap.put("Emily", 22);
personAgeMap.put("John", 30); // Updates John's age to 30
System.out.println(personAgeMap.get("Emily")); // Output: 22
personAgeMap.remove("John"); // Removes the entry for John
System.out.println(personAgeMap.size()); // Output: 1
System.out.println(personAgeMap.keySet()); // Output: [Emily]

Use Case

Scenarios for Use

Maps are best suited for scenarios requiring quick lookups, such as associating keys with specific values. This includes:

  • Database Lookup: Associating unique IDs with database records for quick retrieval.
  • Configuration Settings: Storing configuration settings where keys represent setting names and values represent their settings.
  • Caching: Implementing caches where keys represent the cached item identifiers and values represent the cached data.

Practical Example

In a web application, a map can be used to store user session data, where the session ID is the key and the user information is the value:

javaCopy codeMap<String, UserSession> sessionMap = new HashMap<>();
sessionMap.put("session123", new UserSession("user1", LocalDateTime.now()));
sessionMap.put("session456", new UserSession("user2", LocalDateTime.now()));

// Accessing session data
UserSession session = sessionMap.get("session123");
System.out.println("User: " + session.getUsername());

// Removing a session
sessionMap.remove("session123");

// Checking the size of the map
System.out.println("Active sessions: " + sessionMap.size());

This structure’s ability to ensure unique keys while allowing for quick lookups makes maps an essential tool in many programming applications.

Comparison:

Here is a simple comparison table:

FeatureListSetMap
OrderedYesNoNo (but values can be accessed via keys)
Allows DuplicatesYesNoKeys: No, Values: Yes
Access MethodIndexElementKey
Common Methodsadd(), get(), remove()add(), contains(), remove()put(), get(), remove()
Use CaseOrdered data with duplicatesUnique itemsKey-value pairs

List Vs Set

Here’s a table highlighting the similarities and differences between List and Set in Apex:

AspectListSet
DefinitionAn ordered collection of elements that allows duplicates.An unordered collection of unique elements.
OrderMaintains the order of elements.Does not maintain the order of elements.
DuplicatesAllows duplicate elements.Does not allow duplicate elements.
IndexingElements can be accessed via index.Elements cannot be accessed via index.
UniquenessDoes not ensure uniqueness of elements.Ensures all elements are unique.
Access MethodAccessed by index (e.g., list.get(index)).Accessed by element (e.g., set.contains(element)).
Methodsadd(), get(), remove(), size(), sort().add(), contains(), remove(), size().
FlexibilityCan store objects of any type, including primitives, custom objects, and sObjects.Can store objects of any type, including primitives, custom objects, and sObjects.
Use CaseIdeal for scenarios where the order of elements matters or duplicates are needed.Useful for storing unique items and quickly checking the existence of an element.

This table should help you quickly understand the similarities and differences between List and Set in Apex. If you need further information or examples, feel free to ask!

List Vs Map

Here’s a table highlighting the similarities and differences between List and Map in Apex:

AspectListMap
DefinitionAn ordered collection of elements that allows duplicates.A collection of key-value pairs where each key is unique.
OrderMaintains the order of elements.Does not maintain the order of elements; elements are accessed via keys.
DuplicatesAllows duplicate elements.Keys must be unique; values can be duplicated.
IndexingElements are accessed via index.Elements are accessed via keys.
UniquenessDoes not ensure uniqueness of elements.Ensures uniqueness of keys.
Access MethodAccessed by index (e.g., list.get(index)).Accessed by key (e.g., map.get(key)).
Methodsadd(), get(), remove(), size(), sort().put(), get(), remove(), size(), keySet().
FlexibilityCan store objects of any type, including primitives, custom objects, and sObjects.Can store objects of any type for values; keys can be any primitive or String type.
Use CaseIdeal for scenarios where the order of elements matters or duplicates are needed.Best suited for scenarios requiring quick lookups, such as associating keys with values.

This table provides a clear comparison of the similarities and differences between List and Map in Apex. If you need more details or examples, feel free to ask!

List Class methods in Salesforce Apex

Here are some common List methods in Salesforce Apex:

add()

Adds an element to the end of the list.

public void add(ElementType element)

example

List<String> names = new List<String>();
names.add('John');

get()

Retrieves the element at the specified index.

public ElementType get(Integer index)

example

String name = names.get(0);

remove()

Removes the element at the specified index.

public ElementType remove(Integer index)

example

String removedName = names.remove(0);

size()

Returns the number of elements in the list.

public Integer size()

example

public void sort()

sort()

public void sort()

example

names.sort();

clear()

Removes all elements from the list.

public void clear()

example

names.clear();

isEmpty()

Checks if the list is empty.

public Boolean isEmpty()

example

Boolean isListEmpty = names.isEmpty();

set()

public void set(Integer index, ElementType element)

example

names.set(0, 'Doe');

contains()

Checks if the list contains the specified element.

public Boolean contains(Object element)

example

Boolean hasJohn = names.contains('John');

addAll()

Adds all elements from another list to the current list.

public void addAll(List<ElementType> fromList)

example

List<String> moreNames = new List<String>{'Jane', 'Doe'};
names.addAll(moreNames);

Read more: Java and Cloud Integration

Frequently Asked Questions (FAQs)

What is the difference between the add() and addAll() methods in Apex Lists?

The add() method is used to add a single element to the end of a List, whereas the addAll() method is used to add all elements from another List to the current List.

add() Method:

Definition: Adds one element to the end of the List.

Syntax

public void add(ElementType element)

Example:
List<String> names = new List<String>();
names.add('John');

addAll() Method:

  • Definition: Adds all elements from another List to the end of the current List.
  • Syntax:
public void addAll(List<ElementType> fromList)

Example

List<String> names = new List<String>();
List<String> moreNames = new List<String>{'Jane', 'Doe'};
names.addAll(moreNames);

In summary, use add() for adding a single element and addAll() for adding multiple elements from another List.

Read more: What are Switch Statements in Java?

How can you retrieve an element from a List in Apex?

To retrieve an element from a List in Apex, you use the get() method. This method returns the element at the specified index in the List.

get() Method:

Definition: Retrieves the element at the specified index from the List.

Syntax:

public ElementType get(Integer index)

Example:

List<String> names = new List<String>{'John', 'Jane', 'Doe'};
String name = names.get(1); // Retrieves the element at index 1, which is 'Jane'

The get() method is useful when you need to access a specific element in the List by its index, where indexing starts from 0.

What method would you use to check if a List contains a specific element in Apex?

To check if a List contains a specific element in Apex, you use the contains() method. This method returns a Boolean value indicating whether the specified element is present in the List.

contains() Method:

Definition: Checks if the List contains the specified element.

Syntax

public Boolean contains(Object element)

Example

List<String> names = new List<String>{'John', 'Jane', 'Doe'};
Boolean hasJohn = names.contains('John'); // Returns true if 'John' is in the List, otherwise false

The contains() method is useful for verifying the presence of an element in a List, enabling you to perform conditional logic based on whether the element exists.

Read more: Java Projects with Real-World Applications

How do you remove an element from a List by its index in Apex?

To remove an element from a List by its index in Apex, you use the remove() method. This method removes the element at the specified index and returns the removed element.

remove() Method:

Definition: Removes the element at the specified index from the List.

Syntax:

public ElementType remove(Integer index)

Example

List<String> names = new List<String>{'John', 'Jane', 'Doe'};
String removedName = names.remove(1); // Removes the element at index 1, which is 'Jane', and returns it

The remove() method is useful when you need to delete an element at a particular position in the List. The method shifts any subsequent elements to the left (subtracts one from their indices).

What is the purpose of the sort() method in Apex Lists and how is it used?

The sort() method in Apex Lists is used to sort the elements of the List in ascending order. This method sorts the elements based on their natural ordering or using a custom comparator if provided.

sort() Method:

Definition: Sorts the elements in the List in ascending order.

Syntax

public void sort()

Example

List<Integer> numbers = new List<Integer>{5, 2, 9, 1, 3};
numbers.sort(); // Sorts the List to {1, 2, 3, 5, 9}

The sort() method is particularly useful when you need to organize data in a specific order, such as sorting a list of numbers, dates, or strings alphabetically. This method simplifies the process of arranging elements without the need for manual sorting algorithms.

Comments are closed.