我有四个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循环.或者,如果有任何其他方法可以重构此代码,使其更具可读性和可维护性.
在最外层循环上使用标签,并在break
要跳出所有循环时在语句中包含此标签.在下面的示例中,我已修改您的代码以使用标签OUTERMOST
:
String valueFromObj2 = null; String valueFromObj4 = null; OUTERMOST: 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 if( compareTwoVariable(valueFromObj2, valueFromObj4 )) { break OUTERMOST; } }//fourth loop ends here }//third loop ends here }//second loop ends here }//first loop ends here
将所有循环提取到函数中并使用return.
您可以使用带标签的break语句.这种中断终止了外部陈述
请参阅break语句