Lambda Expression - amresh087/newronaRepos GitHub Wiki
This concept come from lambda calculus
Lamda Programming
- Enable functional programming in java
- Write more readable, maintainable and concise code(very less code)
- To use api very easily and effectively
- To Enable parallel process also
Different between anonymous Inner class and Lamda Expression
-
Anonymous class is class without name Lamda Expression is function without function name(anonymous function)
-
Anonymous class can extend abstract or concrete class Lamda expression can not extend abstract or concrete class
-
Anonymous class can implements any num of interface Lamda expression can implements one interface that contain one abstract method
-
Inside Anonymous class you can declare instance variable but inside Lamda expression can not declare instance variable what ever declare variable that is consider local only.
-
Inside Anonymous class is best uses if interface contain multiple method Lamda expression is best if interface contain one method only.
package com.amresh.functional; interface interf { void m1(); } public class LamdaExample { int x = 10; void m2() { int y = 20; interf itf = () -> { System.out.println(x); System.out.println(y); x=333; //this vaild becuase class level variable y=99; //invaild becuase method leve or local variable }; itf.m1(); } public static void main(String[] args) { LamdaExample le = new LamdaExample(); le.m2(); Thread t=new Thread(()->{ for(int i=0;i<10;i++) { System.out.println(i); } }); t.start(); } }
Note--> Here y = 20 is treated as final
Local variable of method which are reference from lamda expression are final. you can not change value of y in lamda expression
Note--> The main concept in Lamda expression you can assign function as value in interface. So you can say lamda express pass as argument in method or constructor.
for example
String s="amresh"; //this store value
interf itf = () -> {....} // here can see interface store
Thread t1=new Thread(
()->{
for(int i=0;i<=10;i++)
System.ou.println(i);
};
);
Zero parameter:
() -> System.out.println("Zero parameter lambda");
One parameter:
(p) -> System.out.println("One parameter: " + p);
Multiple parameters :
(p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);