Have the following codes with breaking behavior in a for loop:
package test;
import java.util.Arrays;
import java.util.List;
public class Test {
private static List<Integer> integerList = Arrays.asList(1, 2, 3, 4);
public static void main(String[] args) {
countTo2(integerList);
}
public static void countTo2(List<Integer> integerList) {
for (Integer integer : integerList) {
System.out.println("counting " + integer);
if (integer >= 2) {
System.out.println("returning!");
return;
}
}
}
}
trying to express it with Lambda using forEach() will change the behavior as the for loop is not breaking anymore:
public static void countTo2(List<Integer> integerList) {
integerList.forEach(integer -> {
System.out.println("counting " + integer);
if (integer >= 2) {
System.out.println("returning!");
return;
}
});
}
This actually makes sense as the return; statements are only enforced within the lambda expression itself (within the internal iteration) and not for the whole execution sequence, so is there a way to get the desired behavior (breaking the for loop) using the lambda expression?