Java - Lambda Expressions Syntax

Introduction

A lambda expression describes an anonymous function.

The general syntax is

(<LambdaParametersList>) -> { <LambdaBody> }

The list of parameters is declared the same way as methods.

The body of a lambda expression is a block of code enclosed in braces.

The body of a lambda expression may declare local variables.

You can use use statements including break, continue, and return; throw exceptions, etc.

Limitation

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. The return type is inferred by the compiler from the context of its use and from its body.
  • A lambda expression does not have a throws clause.
  • A lambda expression cannot declare type parameters. A lambda expression cannot be generic.

The following table contains some 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
}