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.
A lambda expression does not have four parts.
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 } |