Java Reference
In-Depth Information
In the following snippet of code, the break statement is inside a for-loop statement and it is also inside the body
of a lambda statement. If this break statement is allowed, it will jump out of the body of the lambda expression. This is
the reason that the code generates a compile-time error.
public void test() {
for(int i = 0; i < 5; i++) {
Consumer<Integer> evenIdPrinter = id -> {
if (id < 0) {
// A compile-time error
// Attempting to break out of the lambda body
break;
}
};
}
}
Recursive Lambda Expressions
Sometimes a function may invoke itself from its body. Such a function is called a recursive function . A lambda
expression represents a function. However, a lambda expression does not support recursive invocations. If you need a
recursive function, you need to use a method reference or an anonymous inner class.
The program in Listing 5-22 shows how to use a method reference when a recursive lambda expression is
needed. It defines a recursive method called factorial() that computes the factorial of an integer. In the main()
method, it uses the method reference RecursiveTest::factorial in place of a lambda expression.
Listing 5-22. Using a Method Reference When a Recursive Lambda Expressions Is Needed
// RecursiveTest.java
package com.jdojo.lambda;
import java.util.function.IntFunction;
public class RecursiveTest {
public static void main(String[] args) {
IntFunction<Long> factorialCalc = RecursiveTest::factorial;
int n = 5;
long fact = factorialCalc.apply(n);
System.out.println("Factorial of " + n + " is " + fact);
}
public static long factorial(int n) {
if (n < 0) {
String msg = "Number must not be negative.";
throw new IllegalArgumentException(msg);
}
if (n == 0) {
return 1;
}
 
Search WWH ::




Custom Search