Tuesday, 6 October 2020

How to Use Lambda Expression in Java

Lambda Expression :- Lambda Expression is anonymous function .
 
 General syntax of Lambda Expression 
 
 parameter -> expression
 
 Lambda Expression consist of following three part
 
 1. List of Parameter     : -  List of Parameter describes the parameter pass to expression .
 2. Hyphen with Arrow : - This separate list of parameter from body of lambda expression .
 3. Body of Lambda  :-       Body of Lambda use to write business logic . it can have 
                                            return statement.  
 
 
 How to Use Lambda Expression : - 
 
 1 . Using as in line implementation of functional interface.
 2 . Using as passing argument to method .
 
 
 Function Descriptor 
 
 Lambda Expression can be use to provide the in line implementation of functional interface. So in order to do this Function Descriptor  describe how to write body of Lambda expression  . 

Function Descriptor with no parameter  with no return type 
 
 ()-> body of expression 
 
 Function Descriptor with parameter with no return type 
 
 (parameter1,parameter2)-> body of expression 
 
 
  Function Descriptor with parameter with  return type 
 
 (parameter1,parameter2)-> { body of expression with return statement  }; 
 
  
 Note :- Data type of parameter is optional . it can be inferred  at runtime 


 Lambda Expression Java Application

LamadaExpressionApplication.java
package in.jk.java8;

public class LamadaExpressionApplication {

public static void main(String[] args) {

System.out.println("Lamada Expression Application ....");

System.out.println("\nLamada Expression with no return type  \n");
Adder adder = (num1, num2) -> {
System.out.println("Sum is :: " + (num1 + num2));
};
adder.add(10, 10);
System.out.println("\nLamada Expression with return vlaue  \n");
Multiplier multiplier = (num1, num2) -> {
return num1 * num2;
};
int result = multiplier.multiply(10, 10);
System.out.println("Multiplication  is  :: " + result);

System.out.println("\nLamada Expression Passing as argument to method :: \n");
LamadaExpressionApplication.show((num1, num2) -> num1 * num2, 10, 10);

}

public static void show(Multiplier multiplier, int num1, int num2) {

int result = multiplier.multiply(num1, num2);
System.out.println("Multiplication :: " + result);

}

}

Adder.java

interface Adder {

public void add(int num1, int num2);

}

Multiplier.java

interface Multiplier {

public int multiply(int num1, int num2);
}


Output in Console ....

Lamada Expression Application ....

Lamada Expression with no return type  

Sum is :: 20

Lamada Expression with return vlaue  

Multiplication  is  :: 100

Lamada Expression Passing as argument to method :: 

Multiplication :: 100


No comments:

Post a Comment