Complete Guide to Apex Collections in Salesforce

Complete Guide to Apex Collections in Salesforce

Apex Collections are fundamental data structures used in Salesforce development. They allow developers to store, retrieve, and manipulate groups of data efficiently. Salesforce supports three main types of collections: List, Set, and Map. This document provides an in-depth understanding of each collection type, its use cases, and real-world scenarios with example code.

1. List Collection

A List in Apex is an ordered collection of elements that are accessed using zero-based indices. Lists can contain duplicate elements and maintain the order in which items are added.

✅ Key Characteristics:

  • – Ordered collection
  • – Allows duplicates
  • – Access elements using index

🧑‍💻 Example:

List<String> names = new List<String>();
names.add(‘Alice’);
names.add(‘Bob’);
System.debug(names[0]); // Output: Alice

📘 Real Use Case:

You can store the result of a SOQL query in a List:
List<Account> accList = [SELECT Id, Name FROM Account WHERE Industry = ‘Banking’];

2. Set Collection

A Set is an unordered collection of unique elements. It does not allow duplicate values and is typically used for filtering or ensuring uniqueness.

✅ Key Characteristics:

  • – Unordered collection
  • – No duplicates allowed
  • – Fast membership check

🧑‍💻 Example:

Set<String> uniqueNames = new Set<String>();
uniqueNames.add(‘Alice’);
uniqueNames.add(‘Bob’);
uniqueNames.add(‘Alice’); // Ignored, as it’s a duplicate
System.debug(uniqueNames);

📘 Real Use Case:

Filter unique AccountIds from a list of Contacts:
Set<Id> accIds = new Set<Id>();
for(Contact c : contactList) {
accIds.add(c.AccountId);
}

3. Map Collection

A Map is a collection of key-value pairs. Each unique key maps to a single value, which can be any data type. Maps are extremely useful for associating records by ID or any other unique reference.

✅ Key Characteristics:

  • – Key-value pairs
  • – Keys must be unique
  • – Fast value lookup using key

🧑‍💻 Example:

Map<Id, Account> accMap = new Map<Id, Account>([SELECT Id, Name FROM Account]);
Account a = accMap.get(‘001XXXXXXXXXXXX’);

📘 Real Use Case:

Group Contacts by AccountId:
Map<Id, List<Contact>> conMap = new Map<Id, List<Contact>>();
for(Contact con : [SELECT Id, Name, AccountId FROM Contact WHERE AccountId != null]) {
if (!conMap.containsKey(con.AccountId)) {
conMap.put(con.AccountId, new List<Contact>());
}
conMap.get(con.AccountId).add(con);
}

Real-World Scenario: Grouped Email Notifications

A company wants to send tailored email notifications to contacts grouped by their account. Using Map<Id, List<Contact>>, the development team can fetch all contacts, group them by AccountId, and send one consolidated email per account.

🧑‍💻 Code Snippet:

Map<Id, List<Contact>> groupedContacts = ContactGroupingService.getContactsGroupedByAccount();
for (Id accId : groupedContacts.keySet()) {
List<Contact> conList = groupedContacts.get(accId);
// Send consolidated email
System.debug(‘Sending email to Account: ‘ + accId + ‘ with ‘ + conList.size() + ‘ contacts.’);
}

Leave a Comment

Your email address will not be published. Required fields are marked *