ApexSensei

Drills › Write Apex

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: 0 and Null count: 0

Requirements:

  1. Use a for-each loop over accounts. On each pass, print Visited: plus the name and add 1 to visitedCount.
  2. After the loop, print Visited count: with the count.
  3. Reset emptyCount to 0 before you loop, loop over emptyAccounts, and print Empty count: with the result.
  4. Reset nullCount to 0 before you loop, check that missingAccounts is not null before you loop over it, and print Null 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.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ For loop: number invoices · While a queue has work ›