Maps of sObjects
By the end of this lesson, you'll be able to:
- Build a Map<Id, sObject> from a SOQL query result
- Explain why this pattern avoids a second query inside a loop
- Use a Map<Id, sObject> to look up related records efficiently
Prerequisites: "Maps"
Building a Map<Id, sObject> from a query
List<Account> accounts = [SELECT Id, Name, Industry FROM Account];
Map<Id, Account> accountsById = new Map<Id, Account>(accounts);
Id someAccountId = accounts[0].Id;
System.debug(accountsById.get(someAccountId).Name);
Passing a List<Account> directly into new Map<Id, Account>(...) automatically builds a map keyed by each record's Id — no manual loop needed. This is such a common pattern that Apex has built-in support for it.
The problem this pattern solves
// DON'T DO THIS — a query inside a loop
for (Opportunity opp : opportunities) {
Account acc = [SELECT Name FROM Account WHERE Id = :opp.AccountId]; // a query per iteration!
System.debug(acc.Name);
}
This is exactly the "SOQL-in-a-loop" governor limit problem from Module 7's "Loops and Governor Limits" lesson — a separate query runs for every single opportunity, quickly hitting the 100-query limit with enough records.
The fix: one query, then map lookups
List<Opportunity> opportunities = [SELECT Id, AccountId FROM Opportunity];
Set<Id> accountIds = new Set<Id>();
for (Opportunity opp : opportunities) {
accountIds.add(opp.AccountId);
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);
for (Opportunity opp : opportunities) {
Account relatedAccount = accountsById.get(opp.AccountId);
System.debug(relatedAccount.Name);
}
One query collects the needed Account Ids (using a Set to deduplicate, from this module's first lesson), one query fetches those Accounts, and the Map makes every subsequent lookup instant — regardless of how many opportunities there are. This exact pattern reappears constantly in later modules on triggers and bulkification.
Exercise
Given List<Contact> contacts (each with an Id and Name), build a Map<Id, Contact> keyed by Id using the constructor shortcut.
Show hint
new Map<Id, Contact>(contacts)
Maps of sObjects Quiz
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
Map<Id, sObject> is the single most common Map shape in real Apex code — it lets you look up a Salesforce record by its Id in memory, entirely avoiding a second SOQL query inside a loop.