The Apex Master Class

For Loops in Apex: Collection Iteration (Ep. 29)

4 min read

Subscribe on YouTube

Doing Something To Everything

Back in episode 16 we said collections let you hold 200 records in one variable. Great. Now how do you actually do something to all 200 of them?

You loop. Iteration means walking through a collection one item at a time and running the same code for each.

Apex gives you three loop types. You’ll use one of them about 95% of the time.


The Enhanced For Loop (Use This One)

Apex
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 10];

for (Account acct : accounts)
{
    System.debug('Account name: ' + acct.Name);
}

Read that colon as “in.” For each Account, which I’m calling acct, in the list accounts, do this.

Each time round, acct holds the next record. No counters, no index maths, no chance of running off the end of the list. This is the one you want almost every single time.

It works on Sets too:

Apex
for (Id accountId : accountIds)
{
    System.debug(accountId);
}

And on Maps, though you have to pick whether you’re walking the keys or the values:

Apex
//over the keys, so you can grab each value as you go
for (Id accountId : accountsById.keySet())
{
    Account acct = accountsById.get(accountId);
}

//or straight over the values, if you don't need the keys
for (Account acct : accountsById.values())
{
    System.debug(acct.Name);
}

The Traditional For Loop

The old school version, where you manage the counter yourself:

Apex
for (Integer i = 0; i < accounts.size(); i++)
{
    System.debug(accounts[i].Name);
}

Three parts separated by semicolons: start at 0, keep going while i is less than the size, add one each time round.

Note it’s < and not <=. Remember indices start at zero, so a list of 10 items has positions 0 through 9. Use <= and you’ll ask for position 10, which doesn’t exist, and get List index out of bounds for your trouble.

That right there is why the enhanced loop is better. It cannot make that mistake because there’s no index to get wrong.

So when would you use this one? When you genuinely need the position number, or when you’re modifying the list as you go. Both are rare. If you’re reaching for this out of habit, don’t.


The While Loop

Apex
Integer count = 0;

while (count < 10)
{
    System.debug('Count is ' + count);
    count++;
}

Keeps going as long as the condition is true. Useful when you don’t know in advance how many times you need to go round.

The obvious hazard: forget to change the thing you’re testing and it runs forever. Salesforce will eventually stop you with a CPU timeout, but only after you’ve burned your entire limit doing nothing useful.

Honestly, you’ll write very few while loops in Apex. Almost everything is “do this to each record in this collection,” which is exactly what a for loop is for.


break and continue

Apex
for (Account acct : accounts)
{
    //skip this one, carry on with the rest
    if (acct.Name == null) { continue; }

    //found what we wanted, stop entirely
    if (acct.Name == 'Target Account')
    {
        System.debug('Found it');
        break;
    }
}

continue skips to the next iteration. break abandons the loop altogether.

break is genuinely useful when you’re searching for one thing. Why walk 200 records after you’ve already found it?


The SOQL For Loop

One Apex specific variant worth knowing early. You can put a query straight into the loop declaration:

Apex
for (Account acct : [SELECT Id, Name FROM Account])
{
    System.debug(acct.Name);
}

This is not the same as querying into a list first. It’s better for large data volumes, because it pulls records in chunks of 200 rather than loading everything into memory at once. That keeps you under the heap size limit when you’re dealing with a lot of records.

Important: this does not mean you’re running a query inside a loop. It’s still one query. That distinction matters enormously, and it’s the first thing we’ll get into next episode.


What’s Next

Three loop types, and the enhanced for loop covers nearly everything. Official docs here.

Now, loops are also where new Salesforce developers do the most damage, and it’s always the same handful of mistakes. In the next episode I’ll show you exactly what they are so you never have to learn them the hard way.

See you next time!


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture