There are some rules to make lambda expression more concise.
Example 1:
Let's take an example:
public void displaySum(int a, int b) {
System.out.println(a + b);
}
The valid Lambda expression of above method is:
(int a, int b) -> System.out.println(a + b);
It can be made more concise by taking out the parameter's datatypes.
(a, b) -> System.out.println(a + b);
Note: The type of the parameters can be declared explicitly, or it can be inferred from the context.
Example 2:
Let's take another example:
public int square(int a) {
return a * a;
}
Its equivalent lambda expression is:
n->n*n;
Note:
1. If there are no curly brackets, then the return keyword is not needed.
2. If there is only one parameter in the function, then () is also not needed.
Q1. Write an lambda expression that returns length of string.
Give answer on the comment below :)
How to execute the Lambda expression?
To execute the lambda expression, we use one of the other features of java 8: Functional Interface. We will discuss it in the next post of this series.
Top comments (0)