Java 8 – Lambda Expression (3 Part Series)
1 Java 8 – Lambda Expression 101
2 Java 8 – Lambda Expression Rule
3 Java 8 – Functional Interface
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);
}
Enter fullscreen mode Exit fullscreen mode
The valid Lambda expression of above method is:
(int a, int b) -> System.out.println(a + b);
Enter fullscreen mode Exit fullscreen mode
It can be made more concise by taking out the parameter’s datatypes.
(a, b) -> System.out.println(a + b);
Enter fullscreen mode Exit fullscreen mode
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;
}
Enter fullscreen mode Exit fullscreen mode
Its equivalent lambda expression is:
n->n*n;
Enter fullscreen mode Exit fullscreen mode
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.
Java 8 – Lambda Expression (3 Part Series)
1 Java 8 – Lambda Expression 101
2 Java 8 – Lambda Expression Rule
3 Java 8 – Functional Interface
暂无评论内容