Friday, July 17, 2015

Java 8 : Lambda expression

Lambda expression is a key point to achieve functional programming. It facilitate to make your code more concise. Java developer aware of anonymous class. Now taste the anonymous methods. This can be created using lambda expressions.
-------------------------------------------------------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.
----------------------------------------------------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

Merging two sorted arrays - Big O (n+m) time complexity

 Problem :  Merge the two sorted arrays. Edge case :  Array can empty Arrays can be in different size let getMaxLength = ( input1 , input...