Approach 1 -
Break with a label can be used to exit the outer loop. In this we label the outer loop and use that label when we want to break and exit the outer loop as well.
outerloop:
for (Type type : types) {
for (Type t : types2) {
if (some condition) {
// Do something and break...
break outerloop; // Breaks out of the inner loop
}
}
}
As soon as the condition is matched it will break out the outer lop also.
Approach 2 -
We can extract the loop into a method( possibly static if it is a general method) and return from it on condition match-
public class Test {
public static void main(String[] args) {
//Calling loop
loop();
System.out.println("Done");
}
public static void loop() {
for (Type type : types) {
for (Type t : types2) {
if (some condition) {
// Do something and break...
return; // Breaks out of the inner loop
}
}
}
}
}