Lambda Expression
Lambda Expression:
- Lambda Expression First introduced in LISP Programming Language in 1930
- lambda Expression already in Python,LISP,C,C++,Ruby,Scala.
- java strongly supports OOP but java does not support functional programming. brings benefits of functional programming in java they introduced Lambda Expression.
- Lambda Expression is an anonymous function. i.e function without a name, return type, and without modifiers called an anonymous function.
Normal Code:
public class Test {
public static int squar(int a) {
return a*a;
}
public static void main(String[] args) {
System.out.println("Squar of 4 : " + squar(4));
System.out.println("Squar of 6 : " + squar(6));
}
}
Lambda Expression :
public class Test {
public static void main(String[] args) {
java.util.function.Function<Integer,Integer> f = i->i*i;
System.out.println("Squar of 4 : " + f.apply(4));
System.out.println("Squar of 6 : " + f.apply(6));
}
}
Rules For Lambda Expression :
- if only one line of code inside your method then no need to use {} brackets. for eg: () -> System.out.println("hello");
- for multiple line code we required {} brackets. for eg :(int a,int b) -> {int c = a+b; System.out.println(c);}
- no need mentaion metod arguments data type in lambda Expression because compiler automacically get the data type of arguments. (a,b) -> System.out.println("hello");
- Within {} return keyword is required. for eg: (n)->{return n*n;}
- if only one input parameter is aviable then () is optional. for Ex : n->n*n;
Normal Code :
public void m1(String s){
return s.length();
}
Lambda Expression:
s->s.length();
Calling Lambd Expression :
1. For calling Lambda Expression we required a Functional interface. a functional interface is an interface which
Comments
Post a Comment