Write a Java Program to pass lambda expression as a method argument

Passing lambda expressions as method arguments is a powerful feature of Java 8 and above, which allows us to write concise and flexible code.

In this tutorial, we will explore how to pass a lambda expression as a method argument in Java.


Lambda expressions are anonymous functions that can be used to represent a block of code.

In Java, lambda expressions are used extensively in functional programming, which is a programming paradigm that focuses on the use of functions as the primary building blocks of software.

To pass a lambda expression as a method argument in Java, we need to define a functional interface.

A functional interface is an interface that contains only one abstract method.

We can use the @FunctionalInterface annotation to indicate that an interface is a functional interface.

Here is an example of a functional interface:

@FunctionalInterface
public interface MyFunction {
    int apply(int x, int y);
}

The above interface has only one abstract method, apply(int x, int y).

We can use this interface to define a lambda expression that takes two integer arguments and returns an integer result.

Now, we can pass a lambda expression that implements this interface as a method argument.

Here is an example of a method that takes a lambda expression as an argument:

public class LambdaTest {
    public static void main(String[] args) {
        LambdaTest test = new LambdaTest();

        int result = test.doOperation(10, 5, (x, y) -> x + y);
        System.out.println("Result: " + result);
    }

    public int doOperation(int x, int y, MyFunction func) {
        return func.apply(x, y);
    }
}

In the above example, we create an instance of the LambdaTest class and call the doOperation method with three arguments: 10, 5, and a lambda expression that adds two integer arguments.

The lambda expression (x, y) -> x + y implements the MyFunction interface and returns the sum of its two integer arguments.

When we run the above program, it will output Result: 15, which is the sum of 10 and 5.


In conclusion, passing lambda expressions as method arguments in Java is a powerful feature that allows us to write flexible and concise code.

By defining functional interfaces, we can pass lambda expressions that implement those interfaces as method arguments.

This feature is widely used in functional programming and can greatly improve the readability and maintainability of our code.