How do I break multiple foreach loops?
Use a label on the outermost loop, and include this label in the break
statement when you want to jump out of all the loops. In the example below, I've modified your code to use the label 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
You could use a labeled break statement. This kind of break terminates an outer statement
See The break Statement
See the Branching Statements Java Tutorial for the easiest way, using a label. You can label any or all of the for loops, then use break
or continue
in conjunction with those labels.
An alternative to using labels is to use return
instead. Just refactor your code into a method call to bypass the need to use labels at all.
Extract all the loops into the function and use return.