java8 out of the loop can not be used in the break?
Test found that:
For special written lamada expression java8, you can not use the break, an error message appears;
java8 used in return, will be out of the current cycle, the next cycle to continue, continue similar effect;
java8 using the foreach, but not lamada written expression, can be used normally break or return, directly out of the loop.
public class TestForEachJava8 {
public static void main (String [] args) {
System.out.println ( "C --- ---------------- ");
// use foreach expression lamada BREAK
List <String> C = Arrays.asList (" 6666 "," 7777 "," 8888 ", "9999");
c.stream () forEach (STR -> {.
IF ( "8888" .equals (STR)) {
return; // out of the current cycle, continue to the next round
}
System.out.println (STR) ;
});
the System.out.println("d-------------------");
List<String> d = Arrays.asList("6666", "7777", "8888", "9999");
d.stream().forEach(str ->{
System.out.println(str);
if("8888".equals(str)){
break; //IDE提示错误:break cannot be used outside of a loop or a switch
}
});
System.out.println("a-------------------");
List<String> a = new ArrayList<>();
a.add("1111");
a.add("2222");
a.add("3333");
a.add("4444");
for(String str:a){
if("3333".equals(str)){
break;// out of the loop normal System.out.println (STR);
}
}
System.out.println("b-------------------");
List<String> b = new ArrayList<>();
b.add("1111");
b.add("2222");
b.add("3333");
b.add("4444");
for(String str:b){
if("3333".equals(str)){
return; //也能跳出循环
}
System.out.println(str);
}
}
}
输出:b -------------------22221111A-- -----------------9999888877776666d'-------------------999977776666
c-------------------
1111
2222
Java8 foreach loop out of the break / return
Guess you like
Origin www.cnblogs.com/zhuyeshen/p/12157626.html
Recommended
Ranking