Java Reference
In-Depth Information
A lambda expression consists of a list of parameters and a body that are separated by an arrow ( -> ). The list
of parameters is declared the same way as the list of parameters for methods. The list of parameters is enclosed in
parentheses, as is done for methods. The body of a lambda expression is a block of code enclosed in braces. Like
a method's body, the body of a lambda expression may declare local variables; use statements including break ,
continue , and return ; throw exceptions, etc. Unlike a method, a lambda expression does not have four parts.
A lambda expression does not have a name.
A lambda expression does not have a return type. It is inferred by the compiler from the
context of its use and from its body.
A lambda expression does not have a
throws clause. It is inferred from the context of its use
and its body.
A lambda expression cannot declare type parameters. That is, a lambda expression
cannot be generic.
Table 5-1 contains some examples of lambda expressions and equivalent methods. I have given a suitable
name to methods as you cannot have a method without a name in Java. The compiler infers the return type of
lambda expressions.
Table 5-1. Examples of Lambda Expressions and Equivalent Methods
Lambda Expression
Equivalent Method
(int x, int y) -> {
return x + y;
}
int sum(int x, int y) {
return x + y;
}
(Object x) -> {
return x;
}
Object identity(Object x) {
return x;
}
(int x, int y) -> {
if ( x > y) {
return x;
}
else {
return y;
}
}
int getMax(int x, int y) {
if ( x > y) {
return x;
}
else {
return y;
}
}
(String msg) -> {
System.out.println(msg);
}
void print(String msg) {
System.out.println(msg);
}
() -> {
System.out.println(LocalDate.now());
}
void printCurrentDate() {
System.out.println(LocalDate.now());
}
() -> {
// No code goes here
}
void doNothing() {
// No code goes here
}
 
Search WWH ::




Custom Search