Search code examples
javabreakcontinue

Java - Skipping element of outer loop if condition is true for any element in inner loop


Here's the code:

for ( Element e : elements ){
    boolean shouldContinue = false;
    for ( OtherElement oe : otherElements ){
        if ( e.magicalCondition(oe) ){
            shouldContinue = true;
            break;
        }
    }
    if (shouldContine){
        continue;
    }  
    otherLogic(e);
}

What I want done is checking a condition in the inner loop, if said condition is fulfilled, skip this Element, but otherLogic() should be applied to all other Elements where the condition isn't fulfilled.


Solution

  • I would split using two or three methods and Stream:

    elements.stream()
            .filter(this::shouldApplyOtherLogic)
            .forEach(this::otherLogic);
    
    boolean shouldApplyOtherLogic(Element e) {
      return otherElements.stream().noneMatch(oe -> e.magicalCondition(oe)); // or e::magicalCondition
    }
    

    If you are more comfortable with for, then a second method would still be better:

    for (Element e : elements) {
      if (shouldApplyOtherLogic(e)) {
        otherLogic(e);
      }
    }
    
    boolean shouldApplyOtherLogic(Element e) {
      for ( OtherElement oe : otherElements) {
        if (e.magicalCondition(oe)) {
          return false;
        }
      }
      return true;
    }
     
    

    The quirks is to invert the logic: search element for which you should apply logic then apply logic (rather than finding element for which you don't want to apply logic).

    The method also further encompass what your code is doing.