-> The Lambda expression is used to provide the implementation of an interface which has functional interface.
-> It saves a lot of code.
-> In case of lambda expression, we don't need to define the method again for providing the implementation. Here, we just write the implementation code.
-> Java lambda expression is treated as a function, so compiler does not create .class file.
Functional Interface
-> Lambda expression provides implementation of functional interface.
-> An interface which has only one abstract method is called functional interface.
-> Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.
Syntax
(argument-list) -> {body}
Java lambda expression is consisted of three components.
1) Argument-list: It can be empty or non-empty as well.
2) Arrow-token: It is used to link arguments-list and body of expression.
3) Body: It contains expressions and statements for lambda expression.
Example : Addition of two numbers using lamda expression
@FunctionalInterface
interface Calc{
int add(int n1,int n2);
}
public class Calculation{
public static void main(String[] args) {
Calc addition=(n1,n2)->{
return n1+n2;
};
System.out.println("Addition "+addition.add(10,20));
}
}
Output
Addition 30
No comments:
Post a Comment