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.
CodePudding user response:
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.
CodePudding user response:
for ( Element e : elements ) {
for ( OtherElement oe : otherElements ) {
if (! e.magicalCondition(oe) ) { // negate the result
otherLogic(e); // execute within the if
break;
}
}
// removes all the continue logic overhead
}
CodePudding user response:
What you have mentioned is if condition fulfilled, skip Element
, so I am thinking inner loops else condition need break
:
for (Element e : elements) {
for (OtherElement oe : otherElements) {
if (!e.magicalCondition(oe)) {
otherLogic(e);
} else
break;
}
}