Java Reference
In-Depth Information
Jumps and Exits
Statements such as break , continue , return , and throw are allowed inside the body of a lambda expression. These
statements indicate jumps inside a method and exits from a method. Inside a lambda expression, they indicate jumps
inside the body of the lambda expression and exits from the body of the lambda expressions. They indicate local
jumps and exits in the lambda expressions. Non-local jumps and exits in lambda expressions are not allowed.
The program in Listing 5-21 demonstrates the valid use of the break and continue statements inside the body of
a lambda expressions.
Listing 5-21. Using Break and Continue Statements Inside the Body of a Lambda Expression
// LambdaJumps.java
package com.jdojo.lambda;
import java.util.function.Consumer;
public class LambdaJumps {
public static void main(String[] args) {
Consumer<int[]> printer = ids -> {
int printedCount = 0;
for (int id : ids) {
if (id % 2 != 0) {
continue;
}
System.out.println(id);
printedCount++;
// Break out of the loop after printing 3 ids
if (printedCount == 3) {
break;
}
}
};
// Print an array of 8 integers
printer.accept(new int[]{1, 2, 3, 4, 5, 6, 7, 8});
}
}
2
4
6
 
Search WWH ::




Custom Search