You might have heard of lambda in mathematics.It is a bog change in math and is introduced in 1930’s.It solved complex problems easily.
Java is not first language to use lambda expression. First language which lambda expression is LISP.
There are other languages as well:
C, C++,objective c, c# .net, SCALA, ruby,python …. And Java.
Why Lambda ?
1. Lambda expression is to enable functional programming in Java.
2. To write more readable, maintainable and concise code.
3. To use APIs very easily and effectively.
4. To enable parallel processing.
There is wrong understanding in between developers that Lambda Expression has come to replace anonymous inner classes. Which is totally incorrect.
Basic difference between Anonymous Inner Class and Lambda Expression.
Anonymous Class lambda expression
Class without name function without name
Can extend abstract and can extend,can implement
Concrete class
3. Can implement interface with any only 1 interface which contain single abstract number of methods method (functional interface only)
4. We can declare instance variable can’t declare instance variable, whatever
Variable are considered as local variable.
5. Can be initiated can not
6. this always referer current inner this always refers current outer class
Class object but not outer class object object
7. Best choice if want to handle multiple best choice to handle functional interface
Methods.
8. For every class a separate .class file will no separate class
be generated internally
9. Memory will be allocated in heap inside method area. Inside permanent
Memory of JVM.
Demo Labmda Expression:
interface Interf {
public void m1();
}
public class Test1 {
int x=10;
public void m2(){
int y=20;
//lambda expression
Interf i = () -> {
System.out.println(x);
System.out.println(y);
};
i.m1();
}
public static void main(String[] args) {
Test1 t1 = new Test1();
t1.m2();
}
}
Any local variable which is referenced from lambda expression is always final whether we are declaring or not..In above sample code its y which is local and referenced from lambda expression.
This lambda expression is not executing inside the m2() method.But from t.m2()
You can not change local variable value which is y anywhere within or out of lambda expression.
If you are using local variable, then it becomes final.
Compile Error: Local variable y defined in an enclosing scope must be final or effectively final
If you are not using local variable in lambda expression, then its not final.
We can replace big code with small code and complexity using lambda expression.
Eg.
String s = “sks”;
Below highlighted is a function assigned to interface. :)
Interf i = () -> System.out.println(“hello”);
We are in a position to pass lambda expression to the method as parameter and pass field in constructor.
Eg.
New Thread( () ->{
super(“child thread”);
}; )