Java -如果内循环中任何元素的条件为真,则跳过外循环的元素



代码:

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

我想做的是检查内循环中的条件,如果条件满足,跳过这个Element,但otherLogic()应该应用于所有其他条件不满足的Elements

我会使用两个或三个方法和Stream:

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

如果你更适应for,那么第二种方法仍然会更好:

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;
}

奇怪的是颠倒了逻辑:搜索你应该应用逻辑的元素,然后应用逻辑(而不是找到你不想应用逻辑的元素)。

该方法还进一步包含您的代码正在做什么。

你提到的是如果条件满足,跳过Element,所以我认为内部循环其他条件需要break:

for (Element e : elements) {
for (OtherElement oe : otherElements) {
if (!e.magicalCondition(oe)) {
otherLogic(e);
} else
break;
}
}

最新更新