ApexSensei

Drills › Write Apex

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 Co
  • missingId → Has missing key: false and Missing value: null
  • a loop over keySet() → Loop name: Cedar Labs and Loop name: Northstar Co

Requirements:

  1. Set accountsById with new Map<Id, Account>(accountList), not with put.
  2. Call get(northstarId) and print Fetched account: with its Name.
  3. For missingId, print Has missing key: from containsKey and Missing value: from get.
  4. Loop over accountsById.keySet() and print Loop 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.

Try this drill free

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 ›