Lambda expression is a concise representation of an anonymous function which can be passed as an argument to a method or stored in a variable.
We call it anonymous function because it isn’t associated with a particular class like a method does and it doesn’t have a explicit name like a normal method. Like any regular method a lambda has a list of parameters, body, return type and list of exceptions which can be thrown.
Here are examples of lambda expressions:
When value of lambda expression is stored in a variable:

Object var1 = (Object arg1, Object arg2) -> {System.out.println("Hello Lambda")};
When lambda expression passed as an parameter to another method:
Object var1 = method(Object arg1, (Object arg2, Object arg3) -> {arg2 + arg3});

Lambda expression explained:

Lambda Expression

Lambda Expression

Method signature (Parameters):
Lambda function’s Method signature only have parameters, without any name or return as it’s an anonymous function.
Lambda expression can have 0 or more parameters, same as any other regular method.
//Without parameters
() -> {System.out.println("Hello Lambda")};

//With one parameters

(String hello) -> {System.out.println(hello)};
//With two parameters
(String str1, String str2) -> {System.out.println(str1 + str2)};
You can choose to not declare data type of the parameters, it will in inferred from the context.
//Without defining the data type.
(a,b) -> {a+b}

Note: Either you have to define the data type for all the parameters or none of them. You can’t choose define for some of them.
Lambda Operator (->)
The arrow (->) separates the method signature from the implementation.
Method implementation (Lambda body ):
Body of the Lambda expression can have expression or statements.
1. If there is only one statement in the body, curly braces are not required and return type is same as of body expression.
2. If there are more than one statements, then is must be in curly braces and return type will be as value return form the code block, void if nothing is returned.
Few more example of lambda expression:
//no argument and returns void

() -> {}
//no argument and returns a String Hello Lambda as an expression
() -> "Hello Lambda"
//no argument and returns a String (using an explicit return statement)
() -> {return "Hello Lambda"}

Related Articles

Leave a Reply