I\'ve got a nested loop construct like this:
for (Type type : types) {
for (Type t : types2) {
if (some condition) {
// Do somethin
Labeled break concept is used to break out nested loops in java, by using labeled break you can break nesting of loops at any position. Example 1:
loop1:
for(int i= 0; i<6; i++){
for(int j=0; j<5; j++){
if(i==3)
break loop1;
}
}
suppose there are 3 loops and you want to terminate the loop3: Example 2:
loop3:
for(int i= 0; i<6; i++){
loop2:
for(int k= 0; k<6; k++){
loop1:
for(int j=0; j<5; j++){
if(i==3)
break loop3;
}
}
}
Use Labels.
INNER:for(int j = 0; j < numbers.length; j++) {
System.out.println("Even number: " + i + ", break from INNER label");
break INNER;
}
Refer to this article
Java 8 Stream solution:
List<Type> types1 = ...
List<Type> types2 = ...
types1.stream()
.flatMap(type1 -> types2.stream().map(type2 -> new Type[]{type1, type2}))
.filter(types -> /**some condition**/)
.findFirst()
.ifPresent(types -> /**do something**/);
Java does not have a goto feature like there is in C++. But still, goto
is a reserved keyword in Java. They might implement it in the future. For your question, the answer is that there is something called label in Java to which you can apply a continue
and break
statement. Find the code below:
public static void main(String ...args) {
outerLoop: for(int i=0;i<10;i++) {
for(int j=10;j>0;j--) {
System.out.println(i+" "+j);
if(i==j) {
System.out.println("Condition Fulfilled");
break outerLoop;
}
}
}
System.out.println("Got out of the outer loop");
}
Like @1800 INFORMATION suggestion, use the condition that breaks the inner loop as a condition on the outer loop:
boolean hasAccess = false;
for (int i = 0; i < x && hasAccess == false; i++){
for (int j = 0; j < y; j++){
if (condition == true){
hasAccess = true;
break;
}
}
}
It's fairly easy to use label
, You can break the outer loop from inner loop using the label, Consider the example below,
public class Breaking{
public static void main(String[] args) {
outerscope:
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (condition) {
break outerscope;
}
}
}
}
}
Another approach is to use the breaking variable/flag to keep track of required break. consider the following example.
public class Breaking{
public static void main(String[] args) {
boolean isBreaking = false;
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (condition) {
isBreaking = true;
break;
}
}
if(isBreaking){
break;
}
}
}
}
However, I prefer using the first approach.