Maps: Id to Account
Write Apex · Beginner · 15 min · Runs in your Salesforce Developer org · Free
Scenario. A preparation step needs fast Account lookup by Id before any database work.
Build an Id-to-Account Map from a List, look up known and missing keys, and loop over every key.
What you will learn
A Map<Id, Account> stores each Account under its Id. get(key) reads one, containsKey(key) checks for one, and keySet() gives every key. Build a map from a list in one step:
Map<Id, Account> byId = new Map<Id, Account>(accountList);
for (Id key : byId.keySet()) {
System.debug(byId.get(key).Name);
}
Gotcha. get on a missing key returns null. Reading .Name from that null throws an error.
The task
Build an Id-to-Account Map from a List, look up a known key and a missing key, and loop over every key.
Examples:
get(northstarId)→Fetched account: Northstar ComissingId→Has missing key: falseandMissing value: null- a loop over
keySet()→Loop name: Cedar LabsandLoop name: Northstar Co
Requirements:
- Set
accountsByIdwithnew Map<Id, Account>(accountList), not withput. - Call
get(northstarId)and printFetched account:with its Name. - For
missingId, printHas missing key:fromcontainsKeyandMissing value:fromget. - Loop over
accountsById.keySet()and printLoop name:plus each Account's Name.
Starter code
Id cedarId = Id.valueOf('001000000000001');
Id northstarId = Id.valueOf('001000000000002');
Id missingId = Id.valueOf('001000000000099');
List<Account> accountList = new List<Account>{
new Account(Id = cedarId, Name = 'Cedar Labs'),
new Account(Id = northstarId, Name = 'Northstar Co')
};
Map<Id, Account> accountsById = null;
When it passes
Northstar Co is found by its Id, the missing Id gives false and null with no error, and the loop prints both names.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.
‹ Lists of Opportunities · Remove duplicate emails with a Set ›