(Lambda Parameter List) -> { LambdaBody }
Lambda expression takes one argument & returns multiple of 2 of the parameter
(int a) -> { return a*2; }
Takes 2 argument & returns the sum.
(int a, int b) -> { return a + b; }
Another way to achieve the above result.
the block is without a scope ( flower braces {} ), so no need to write return
(int a, int b) -> a + b
Nothing restricts to single line
(int a, int b) -> {
int x = a + b;
if ( x % 2 ){
x = x * 2;
}
return x;
}
Taking no arguments and returning "Hello World"
() -> "Hello World"
Takes nothing & return type is void
() -> { System.out.println("Dummy print"); }
Type fewer parameters. All parameters should be typeless
(a,b) -> {}
Explicit Lambda Expression - Lambda Expression where explicitly type is mentioned.
(int a, int b) -> a + b
Implicit lambda Expression - Lambda Expression where no type is mentioned, a type is inferred from the way lambda is used. The expression that takes
(a,b) -> {}
@FunctionalInterface
interface DoStudy {
public String doEnjoyStudy(String name);
}
public class LambdaProg {
//timeToStudy function takes function as an argument & data the function will work on as an argument
public static void timeToStudy(DoStudy d, String name){
System.out.println(d.doEnjoyStudy(name));
}
public static void main(String[] args) {
//Passing a lambda expression that takes one argument & returns string to function.
timeToStudy((String name) -> "Hello World from "+ name,"zekeLabs");
}
}
Keywords : Java-8 Functional-Programming