how to use Lambda expressions in java?

               Java 8 has an important functionality called lambda expressions. It involves functional interfaces. Functional interfaces are the one which has single abstract method.

Syntax of the lambda expression is given below.

(parameters) -> body

Where

Parameters – It holds the input value.

è -> - It is the one which separates the parameters and body.

Body – It is the code to be executed.

Eg:

The parameters may be single or multiple in number.

(a)-> a+a

(a,b)-> a-b

(a,b,c)-> a+b+c

How to use lambda expressions???

              Generally, Lambda expressions are used to pass arguments to functions. It can be stored as variables or method parameters. But the type should be an interface of single method.

Java Program to use lambda expressions:

  • è In the beginning, create an interface SumInterface. It is a functional interface which has single method “add”. “add” method has two integer parameters.
  • è Next, create a public class “SumLambdaExample” which has the main method. So, save this program as “SumLambdaExample.java”.
  • è Furthermore, create an object for interface addition. Create a lambda expression for addition of two numbers and store it to addition (interface object).
  • è Finally, print the sum value by calling the function sum with two parameters.

   interface SumInterface {

       int add(int a, int b);

   }

   public class SumLambdaExample {

       public static void main(String[] args) {

           SumInterface addition = (a, b) -> a + b;

           System.out.println("Sum of the two numbers are: " + addition.add(65, 43));

       }

   }

While running this program, the user will get this output.

In the same way, you can use the lambda expressions for other arithmetic operations also.

Here are the sample codes.

Replace the first code by others for your program.

   interface SumInterface

   interface SubInterface

   interface mulInterface

   interface divInterface

int add(int a, int b);

int sub(int a, int b);

int mul(int a, int b);

int div(int a, int b);

           SumInterface addition =

 (a, b) -> a + b;

 

           SubInterface subtraction=

(a, b) -> a - b;

 

           mulInterface

multi  = (a, b) -> a * b;

 

           divInterface division = (a, b) -> a / b;

 

addition.add(65, 43))

subtraction.sub(65, 43))

multi.mul(15, 14))

division.div(45, 9))

 These are the ways to use lambda expressions in java programs.

No comments:

Post a Comment