Beginner
25 min read
Lists
By the end of this lesson, you'll be able to:
- Choose the right collection type — List, Set, or Map — for a given problem
- Build a Map keyed by record Id from a SOQL query
Prerequisites: If Statements and Loops
Three collection types, three jobs
- List — an ordered collection that allows duplicates. Reach for this by default.
- Set — an unordered collection with no duplicates. Perfect for deduplicating Ids or values.
- Map — key-value pairs. In Apex, you'll most often see
Map<Id, sObject>to look up a record by its Id in memory, instead of re-querying it.
Building a Map from a query
List<String> names = new List<String>{'Ana', 'Ben', 'Cy'};
Set<Id> uniqueIds = new Set<Id>();
Map<Id, Account> accountsById = new Map<Id, Account>();
for (Account a : [SELECT Id, Name FROM Account LIMIT 5]) {
accountsById.put(a.Id, a);
}
Exercise
Given a List<Contact>, build a Set<String> containing the unique email domains (the part after '@') across all contacts.
Show hint
String domain = email.substringAfter('@'); then add it to your Set.
APEX
Lists, Sets, and Maps — Quick Check
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
List preserves order and allows duplicates. Set enforces uniqueness. Map stores key-value pairs and is the standard way to look up records by Id without a second SOQL query.