A lambda expression, introduced in Java 8 is similar to a block of code resembling an anonymous function that can be passed to constructors or methods for execution as an argument.
Examples:
a)() -> System.out.println("Hello Lambda")
b)(int x) -> 3
x -> {
In the first example :
System.out.println(x + 2);
return x +3;
}
()
identifies the lambda's parameter list (there are no parameters),
->
indicates that the expression is a lambda
System.out.println("....")
is the code to be executed which prints the string "Hello Lambda".
In the Second Example:
(x)
identifies the lambda's parameter list (x is an input parameter),
->
indicates that the expression is a lambda
System.out.println("....")
is the code to be executed which calculates the value of x + 2 and prints it. Also assigns a value of x+3 = 6 to variable x which had an initial value of 3.