Lambda Expression

 Lambda Expression:

  1. Lambda Expression First introduced in LISP Programming Language in 1930
  2. lambda Expression already in Python,LISP,C,C++,Ruby,Scala.
  3. java strongly supports OOP but java does not support functional programming. brings benefits of functional programming in java they introduced Lambda Expression.
  4. 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 :

  1. if only one line of code inside your method then no need to use {} brackets. for eg: () -> System.out.println("hello");
  2. for multiple line code we required {} brackets. for eg :(int a,int b) -> {int c = a+b; System.out.println(c);}
  3. 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");
  4. Within {} return keyword is required. for eg: (n)->{return n*n;}
  5. if only one input parameter is aviable then () is optional. for Ex : n->n*n;

Examples :
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

Popular posts from this blog

public static void main(String [] args) - Full Explanation

Coding Problem 3 - Weather Observation Station 7 [HackerRank - SQL]

Date Range Picker In Angular 10