Collections in Salesforce Apex

Apex Collections in Salesforce Apex: Lists, Sets, and Maps

In Salesforce Apex, collections are used to group multiple elements into a single entity. Apex provides three types of collections: Lists, Sets, and Maps. Each serves a different purpose and has unique characteristics. Let’s dive into each type with detailed explanations and original examples.

1. Lists in Apex

A List is an ordered collection of elements, where each element is assigned a specific index starting from zero. Lists allow duplicate values and are ideal when you need to maintain the order of elements or access elements by their position.

Characteristics of Lists:

  • Ordered: Elements are stored in the order they are added.
  • Indexed: Elements can be accessed using their index.
  • Allows Duplicates: Lists can contain duplicate elements.

Example: Creating and Using a List in Apex

Let’s consider a scenario where we need to store the names of employees in a department.

public class EmployeeManager {
    public void manageEmployees() {
        // Creating a List of employee names
        List<String> employeeNames = new List<String>();
        
        // Adding employee names to the List
        employeeNames.add('John Doe');
        employeeNames.add('Jane Smith');
        employeeNames.add('Alice Johnson');
        employeeNames.add('John Doe'); // Duplicate entry

        // Iterating through the List and printing employee names
        for (Integer i = 0; i < employeeNames.size(); i++) {
            System.debug('Employee ' + (i + 1) + ': ' + employeeNames[i]);
        }
        
        // Accessing an employee name by index
        String firstEmployee = employeeNames[0];
        System.debug('First Employee: ' + firstEmployee);
    }
}

Explanation:

  • We create a List<String> called employeeNames to store the names of employees.
  • Names are added to the list using the add() method. Note that we add ‘John Doe’ twice to demonstrate that Lists allow duplicates.
  • The for loop iterates through the List using the size() method to determine the number of elements.
  • We access the first employee’s name using the index 0 and print it.

2. Sets in Apex

A Set is an unordered collection of unique elements. Sets are useful when you want to store a group of items where duplicates are not allowed, and the order of elements is not important.

Characteristics of Sets:

  • Unordered: The order of elements is not maintained.
  • No Duplicates: Each element must be unique.

Example: Creating and Using a Set in Apex

Let’s extend the previous example to ensure that each employee name is unique.

public class UniqueEmployeeManager {
    public void manageUniqueEmployees() {
        // Creating a Set of unique employee names
        Set<String> uniqueEmployeeNames = new Set<String>();
        
        // Adding employee names to the Set
        uniqueEmployeeNames.add('John Doe');
        uniqueEmployeeNames.add('Jane Smith');
        uniqueEmployeeNames.add('Alice Johnson');
        uniqueEmployeeNames.add('John Doe'); // Attempt to add duplicate entry

        // Iterating through the Set and printing employee names
        for (String name : uniqueEmployeeNames) {
            System.debug('Employee Name: ' + name);
        }
        
        // Checking if a specific name exists in the Set
        Boolean exists = uniqueEmployeeNames.contains('John Doe');
        System.debug('Is John Doe in the Set? ' + exists);
    }
}

Explanation:

  • We create a Set<String> called uniqueEmployeeNames.
  • Names are added using the add() method. Even though ‘John Doe’ is added twice, the Set only stores unique values, so the duplicate is ignored.
  • We use a for-each loop to iterate through the Set and print the names. Since Sets are unordered, the output order may vary.
  • The contains() method checks if ‘John Doe’ exists in the Set.

3. Maps in Apex

A Map is a collection of key-value pairs, where each key is unique, and each key maps to a specific value. Maps are ideal when you need to quickly retrieve a value based on a specific key.

Characteristics of Maps:

  • Key-Value Pairs: Each entry in a Map consists of a key and a corresponding value.
  • Unique Keys: Keys must be unique, but values can be duplicated.
  • Unordered: Maps do not maintain the order of entries.

Example: Creating and Using a Map in Apex

Consider a scenario where we need to store employee IDs and their corresponding names.

public class EmployeeIDManager {
    public void manageEmployeeIDs() {
        // Creating a Map to store employee IDs and names
        Map<Integer, String> employeeIDMap = new Map<Integer, String>();
        
        // Adding employee IDs and names to the Map
        employeeIDMap.put(1001, 'John Doe');
        employeeIDMap.put(1002, 'Jane Smith');
        employeeIDMap.put(1003, 'Alice Johnson');
        employeeIDMap.put(1004, 'John Doe'); // Duplicate value, but different key

        // Iterating through the Map and printing employee IDs and names
        for (Integer empID : employeeIDMap.keySet()) {
            System.debug('Employee ID: ' + empID + ', Name: ' + employeeIDMap.get(empID));
        }
        
        // Retrieving an employee name by their ID
        String employeeName = employeeIDMap.get(1002);
        System.debug('Employee with ID 1002: ' + employeeName);
    }
}

Explanation:

  • We create a Map<Integer, String> called employeeIDMap to store employee IDs and names.
  • Employee IDs (keys) are added with their corresponding names (values) using the put() method. Keys must be unique, but the values can be the same (as shown with ‘John Doe’).
  • We iterate through the Map using the keySet() method, which returns a Set of all keys in the Map. For each key, we retrieve the corresponding value using the get() method.
  • We demonstrate how to retrieve a specific employee’s name using their ID by calling get(1002).

Summary

  • Lists are ordered collections that allow duplicates and provide indexed access.
  • Sets are unordered collections that enforce uniqueness among elements.
  • Maps store key-value pairs, allowing quick retrieval of values based on unique keys.

These collections are fundamental tools in Salesforce Apex, enabling developers to efficiently manage and manipulate data. Understanding when and how to use Lists, Sets, and Maps can significantly enhance the effectiveness and performance of your Apex code.


Tutorials Deck

TutorialsDeck is striving to provide the best learning material on technical and non-technical subjects.

Languages

Web Technologies

Database

Trending Technologies

© 2024. All rights reserved.

Contact Us @ tutorialsdeck06@gmail.com