Java program to pass lambda expression as a method argument

https://w‮i.ww‬giftidea.com

In Java, you can pass lambda expressions as method arguments by defining the method parameter as a functional interface.

Here's an example program that demonstrates how to pass a lambda expression as a method argument:

public class LambdaAsArgument {
    public static void main(String[] args) {
        // Define a lambda expression
        MyLambda myLambda = (String s) -> System.out.println(s);

        // Pass the lambda expression as an argument to the method
        performAction(myLambda, "Hello World!");
    }

    // Define a functional interface
    interface MyLambda {
        void performAction(String s);
    }

    // Define a method that takes a lambda expression as an argument
    public static void performAction(MyLambda lambda, String s) {
        lambda.performAction(s);
    }
}

In this program, we define a functional interface MyLambda that has a single method performAction that takes a String parameter. We then define a lambda expression that implements this interface and prints the input string to the console.

Next, we define a method called performAction that takes a lambda expression of type MyLambda as its first argument and a String as its second argument. Inside the method, we call the performAction method of the lambda expression with the input string as its argument.

Finally, we call the performAction method with the lambda expression and a string as arguments.

When you run the program, the output will be:

Hello World!

As you can see, the program successfully passes the lambda expression as a method argument and executes it inside the method.