ApexSensei

Drills › Write Apex

While a queue has work

Write Apex · Beginner · 12 min · Runs in your Salesforce Developer org · Free

Scenario. A small task queue must be worked first in, first out, and the loop must stop on its own.

Work through an in-memory queue from the front with a while loop until it is empty, and show an empty queue does no work.

What you will learn

A while loop repeats as long as its test is true. It fits when you don't know the count up front, like working through a list until it is empty.

while (!workQueue.isEmpty()) {
    String item = workQueue.remove(0);
}

remove(0) takes the first item out and returns it.

Gotcha. Each pass must get closer to the end. If the list never shrinks, the loop never stops, and Salesforce ends the run with a CPU time limit error.

The task

Work through a queue of tasks from the front until it is empty, then show that an empty queue does no work.

Examples:

  • each pass → Processing: Validate, then Processing: Enrich, then Processing: Route
  • after the loop → Processed count: 3 and Remaining work: 0
  • a queue that starts empty → Empty processed: 0

Requirements:

  1. Loop while workQueue still has items.
  2. On each pass, take out the first item with remove(0), print Processing: plus the item, and add 1 to processedCount.
  3. After the loop, print Processed count: and Remaining work: (the queue's size).
  4. Reset emptyProcessed to 0 before the loop, run the same loop on emptyQueue, and print Empty processed: with the result.

Starter code

List<String> workQueue = new List<String>{ 'Validate', 'Enrich', 'Route' };
Integer processedCount = 0;

List<String> emptyQueue = new List<String>();
Integer emptyProcessed = 0;

When it passes

The three tasks print in order, the count is 3, the queue ends empty, and the empty queue counts 0 passes.

Try this drill free

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

‹ For-each over Accounts · Lists of Opportunities ›