How to break out of nested loops in Java?

0 votes
427 views
asked Jan 9, 2016 by Hitesh Garg (127 points)  

While executing nested loops I want to exit every loop once the condition is matched. I have following loop

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do something and break...
             break; // Breaks out of the inner loop
         }
    }
}

Now how can I break out of both loops because break statement works for single loop only.

Note - I don't want to put the inner loop in a different method.

2 Answers

+2 votes
answered Jan 10, 2016 by Hitesh Garg (127 points)  
selected Jan 13, 2016 by Hitesh Garg
 
Best answer

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
                   }
             }
         }
    }
}
+1 vote
answered Jan 9, 2016 by Anshul Gupta (20 points)  
edited Jan 9, 2016 by Hitesh Garg

You can keep a single flag. After first break,revert the flag value,and after the first loop you can check your flag and can descide if you want to break or not.

for eg:

int flag=0;

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do something and break...
            flag=1;
             break; // Breaks out of the inner loop
         }
    }

  if(flag==1){
   break;
  }
}
Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.
...