For-each over Accounts
Write Apex · Beginner · 12 min · Runs in your Salesforce Developer org · Free
Scenario. A preview step checks Account names that are already in memory, before any database work.
Loop over in-memory Accounts with for-each, count them, and handle an empty List and a null List safely.
What you will learn
A for-each loop visits every item in a list, in order, with no index to manage.
for (Account acct : accounts) {
System.debug(acct.Name);
}
Read it as "for each Account acct in accounts". An empty list is safe: the body runs zero times.
Gotcha. A null list is not an empty list. Looping over null throws a NullPointerException, so check != null first.
The task
Loop over three Accounts in memory and print each name, then loop safely over an empty list and a null list.
Examples:
- first pass →
Visited: Cedar Labs - after the loop →
Visited count: 3 - empty list and null list →
Empty count: 0andNull count: 0
Requirements:
- Use a for-each loop over
accounts. On each pass, printVisited:plus the name and add 1 tovisitedCount. - After the loop, print
Visited count:with the count. - Reset
emptyCountto 0 before you loop, loop overemptyAccounts, and printEmpty count:with the result. - Reset
nullCountto 0 before you loop, check thatmissingAccountsis not null before you loop over it, and printNull count:with the result.
Starter code
List<Account> accounts = new List<Account>{
new Account(Name = 'Cedar Labs'),
new Account(Name = 'Northstar Co'),
new Account(Name = 'Bluebird Goods')
};
Integer visitedCount = 0;
List<Account> emptyAccounts = new List<Account>();
Integer emptyCount = 0;
List<Account> missingAccounts = null;
Integer nullCount = 0;
When it passes
All three names print once, in order, and the count is 3. The empty list and the null list both count 0, with no error.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.