Breaking out of a nested loop

Just for a bit of background I am trying to write a Depth First Sort in Apex. I have been successful writing the method using recursion but when testing with some large data volumes I have hit the Stack Depth Governor Limit.

I am now trying to implement the iterative algorithm (on the wikipedia page). The problem I am facing is best explained using the code snippet below:

while(!stack.isEmpty()) {
    frame = stack.top();
    for (Frame child : frame.children()) {
         if (some condition) {
             continue; //on the while loop, not the for loop
         }
    }
    //this line of code must only execute if 'some condition' is false for all children
    stack.pop();
}

A quick search turns up how to do this in java: Breaking out of nested loops in Java.
But apex doesn’t support named loops, what would be the cleanest way of doing this in apex?

Answer

One easy way, and which gives some nice structure to the code is to make the inner loop a separate function, e.g.

while(!stack.isEmpty()) {
    Frame frame = stack.top();
    if (frameCondition(frame))
        continue;
    frame.pop();
}

boolean frameCondition(Frame f) {
    for (Frame c : f.children()) {
         if (some condition)
              return true;
    }
    return false;
}

Attribution
Source : Link , Question Author : Daniel Blackhall , Answer Author : superfell

Leave a Comment