参见英文答案 > How do I break out of nested loops in Java?????????????????????????????????????33个
我有四个foreach循环遍历集合并根据条件执行某些操作.
这是我现在写的代码:
boolean breakFlag = false;
String valueFromObj2 = null;
String valueFromObj4 = null;
for(Object1 object1: objects){
for(Object2 object2: object1){
// I get some value from object2
valueFromObj2 = object2.getSomeValue();
for(Object3 object3 : object2){
for(Object4 object4: object3){
// Finally I get some value from Object4.
valueFromObj4 = object4.getSomeValue();
// Compare with valueFromObj2 to decide either to break all the foreach loop
breakFlag = compareTwoVariable(valueFromObj2, valueFromObj4 );
if(breakFlag){break;}
} // fourth loop ends here
if(breakFlag){break;}
} // third loop ends here
if(breakFlag){break;}
} // second loop ends here
if(breakFlag){break;}
} // first loop ends here
主要对象(代码中的对象)来自第三方提供程序SDK,因此我无法更改该部分的任何内容.我想询问Stack Overflow社区是否有更好的方法来打破所有四个foreach循环.或者,如果有任何其他方法可以重构此代码,使其更具可读性和可维护性.