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, thenProcessing: Enrich, thenProcessing: Route - after the loop →
Processed count: 3andRemaining work: 0 - a queue that starts empty →
Empty processed: 0
Requirements:
- Loop while
workQueuestill has items. - On each pass, take out the first item with
remove(0), printProcessing:plus the item, and add 1 toprocessedCount. - After the loop, print
Processed count:andRemaining work:(the queue's size). - Reset
emptyProcessedto 0 before the loop, run the same loop onemptyQueue, and printEmpty 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.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.