How to pass a lambda expression as a method argument in java??

                Lambda expression is introduced in Java SE8. It is used in functional interfaces. Functional interface has a single abstraction method. This is a block of code that doesn’t belong to any class.

Features:

  •   The functionality can be a method.
  • ·       The method is independent one.
  • ·       This function is used anywhere whenever the program needs.

How to pass a lambda expression as a method argument in java:

              It can be done many ways. Generally, we follow two methods.

1.      1. Using Runnable

2.       2.Using custom functional interface

1.Using Runnable :

       This method starts from creating a class “Main3” and save the program as “Main3.java”. In the public static void main(), add the lambda expression to print “Welcome to java Programming!”

Next, create a separate function execute with Runnable  variable action.

Now, call action.run().

public class Main3 {

    public static void main(String[] args) {

        //using a lambda expression as a method argument.

        execute(() -> System.out.println("Welcome to java Programming!"));

    }

    public static void execute(Runnable action) {

        action.run();

    }

}

This program gives you the below output.



2.Using custom functional interface

    A functional interface creates abstract method. Here, “condition” is the functional interface. The abstract method is “find”. It has two integer arguments.

A class “Main4” is created. It passes a lambda expression as argument. It adds two integer values.

Another function is created to call the lambda arguments.

Here, is the program.

interface condition {

    int find(int x, int y);

}

public class Main4 {

    public static void main(String[] args) {

        // Passing a lambda expression as a method argument

        int res = conditionChecking(45, 36, (x, y) -> x + y);

        System.out.println("Result: " + res);

    }

    public static int conditionChecking(int x, int y, Operation operation) {

        return operation.find(x, y);

    }

}

While executing this program, you get the below output.

These are the ways to pass a lambda expression as a method argument in java.

No comments:

Post a Comment