Collections & Data Structures in Apex

Share

List, Set & Map in Apex

What Are Collections?

Collections are used to store multiple values in one variable.
They are essential in Apex for bulk processing and performance.

Simple Explanation

Collections are like containers that hold many items together.


List (Ordered & Allows Duplicates)

When to Use List

  • Order matters

  • Duplicates are allowed

Real-Life Example

A shopping list where items can repeat.

Code Example

List<String> names = new List<String>{'Alex', 'Sam', 'Alex'};
System.debug(names);

Set (Unique & Unordered)

When to Use Set

  • No duplicates allowed

  • Order does not matter

Real-Life Example

A class attendance sheet where each student appears only once.

Code Example

Set<String> cities = new Set<String>{'London', 'Paris', 'London'};
System.debug(cities);

Map (Key-Value Pair)

When to Use Map

  • Fast data lookup

  • One value per unique key

Real-Life Example

A dictionary:

  • Word = Key

  • Meaning = Value

Code Example

Map<Id, Account> accountMap = new Map<Id, Account>();

Gist (Quick Revision)

  • List → Ordered, allows duplicates

  • Set → Unique values only

  • Map → Key-value lookup


Nested & Complex Collections

What Are Nested Collections?

Nested collections store collections inside other collections.

Simple Explanation

A box inside another box.


Real-Life Example

A school:

  • Classes (List)

  • Each class has students (List inside List)


Code Example

Map<String, List<String>> classStudents = new Map<String, List<String>>();

classStudents.put('ClassA', new List<String>{'Tom', 'Sam'});
classStudents.put('ClassB', new List<String>{'Alex'});

Why Nested Collections Matter

  • Handling parent-child data

  • Working with related records

  • Bulk processing


Gist (Quick Revision)

Nested collections help manage complex data relationships efficiently.


Common Collection Patterns in Apex

Pattern 1: Avoid SOQL Inside Loops (Very Important)

❌ Bad Practice

for(Account acc : accounts){
    Contact c = [SELECT Id FROM Contact WHERE AccountId = :acc.Id];
}

✅ Good Practice

Map<Id, Account> accMap = new Map<Id, Account>(accounts);

Pattern 2: Using Set to Remove Duplicates

Set<Id> accountIds = new Set<Id>();

Pattern 3: Map for Fast Lookup

if(accountMap.containsKey(accId)){
    Account acc = accountMap.get(accId);
}

Career Coach Tip

Interviewers love collection questions because:

  • They test performance knowledge

  • They reveal real-world Apex experience

Mastering collections = mastering Apex performance


Gist (Quick Revision)

Use Lists for order, Sets for uniqueness, and Maps for fast access.
Combine them to write efficient, scalable Apex code.

  • January 5, 2026