Lambda expression is a Java 8 feature, which helps the developer to simplify syntax of anonymous interface implementation whenever required.
Interface is defined anonymously in earlier Java Implementation in the below old syntax., which is very much reduced in Java 8 lambda implementation, comparison of the below example provide a clear view of Lambda expression.
1. Native Java Implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class NativeJavaExample { public static void main(String[] args) { Calculator additionCalculator = new Calculator(new Operation(){ @Override public int process(int x, int y) { return x+y; } }); Calculator subtractCalculator = new Calculator(new Operation(){ @Override public int process(int x, int y) { return x-y; } }); System.out.println("Addition Result :" + additionCalculator.getResult(10, 12)); System.out.println("Subtraction Result:" + subtractCalculator.getResult(22, 8)); } } |
In this example, Calculator is a class, where Operation is inner object implementation, and the actual operation process is not defined in the application, operation implementation is defined when the Calculator Object is created.
Hence Interface is implemented anonymously by the Composite class ‘Calculator’.
2. Lambda Java Implementation:
In this example, Using Lambda expression, we can defining the operation object for additionCalculator and subtractCalculator in a very much quicker way. ->
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
/** * @author tutorialflow.com */ public class LambdaJavaExample { public static void main(String[] args) { Operation additionLambdaOperation = (x, y) -> { return (x+y); }; Operation subtractLambdaOperation = (x, y) -> (x-y); Calculator additionCalculator = new Calculator(additionLambdaOperation); Calculator subtractCalculator = new Calculator(subtractLambdaOperation); Calculator multiplyCalculator = new Calculator((x,y)->(x*y)); System.out.println("Addition Result :" + additionCalculator.getResult(10, 12)); System.out.println("Subtraction Result:" + subtractCalculator.getResult(22, 8)); System.out.println("Multiplication Result:" + multiplyCalculator.getResult(20, 6)); } } class Calculator { Operation operation; public Calculator(Operation oper) { this.operation = oper; } public int getResult(int x, int y){ return operation.process(x, y); } } interface Operation { public int process(int x,int y); } |