-------------------------------------------------------Java 8--------------------------------------------------------
package com.ran;
@FunctionalInterface
interface ExpressionHolder {
int eval(int a,int b);
}
public class LamdaExpressionInJava8 {
//Functional interface
public static void main(String[] args) {
ExpressionHolder addExpression=(a1,a2)-> a1 + a2;
System.out.println(addExpression.eval(1, 2));
}
}
-----------------------------------------------------------------------------------------------------------------------
From the above code the high lighted portion is sample for lambda expression.
Here ExpressionHolder is a interface which has apply method in it. Int the case of traditional way of java development would go with implementation class for ExpressionHolder or anonumous class. Here the complete implementation has covered in the lambda expression. This is inline implementation of the functional interface.
Method parameters --> functional body
For comparison purpose I have given the java 7 code also with the sample model. This code may help to understand the lambda expression in best.
Anonumous class implemenation of ExpressionHolder has been exhibited here.
Anonumous class implemenation of ExpressionHolder has been exhibited here.
----------------------------------------------------Java 7----------------------------------------------------
package com.ran.java7;
interface ExpressionHolder {
int apply(int a,int b);
}
public class LamdaExpressionInJava7 {
//Functional interface
public static void main(String[] args) {
ExpressionHolder addExpression=new ExpressionHolder() {
@Override
public int apply(int a, int b) {
return a+b;
}
};
System.out.println(addExpression.apply(1, 2));
}
}
----------------------------------------------------------------------------------------------------------------
No comments:
Post a Comment