'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 1:[1]
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.
Solution 2:[2]
What you have mentioned is if condition fulfilled, skip Element
, so I am thinking inner loops else condition needs break
:
for (Element e : elements) {
for (OtherElement oe : otherElements) {
if (!e.magicalCondition(oe)) {
otherLogic(e);
} else
break;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |