What is Lambda Expression?
Lambda Expression is a feature to implement functional logic without method name, class name in a object oriented programming. It simplifies the way functional logic implemented in object oriented programming.
Where Lambda Expressions can be used?
In Object Oriented Programming, A complex method would be broken into multiple methods by grouping logic statements to reduce complexity for better reading and maintenance. But those new methods would not be reused for any other purposes. Here, Lambda expression can be used to implement the functional logic in elegant way rather than creating multiple methods or anonymous classes.
Syntax:
Here, (parameters as comma separated) are not mandatory, it can be empty parenthesis if no parameter required.
Simple Example:
public class LambdaCalculate {
public static void main(String[] args){
int var1 = 6;
int var2 = 5;
Calculate addition = (int a, int b) -> { return a+b; };
int result1 = addition.calculate(var1, var2);
System.out.println("lambda.LambdaCalculate.main() :: " + result1);
Calculate subtraction = (int a, int b) -> { return a-b; };
int result2 = subtraction.calculate(var1, var2);
System.out.println("lambda.LambdaCalculate.main() :: " + result2);
}
}
public interface Calculate{
public int calculate(int a, int b);
}
No comments:
Post a Comment