Sameera De Silva
2 min readApr 22, 2023

How to pass Lambda expression to another class?

We often need to pass our lambda expressions to other classes, so let’s see how to achieve this.

In this example, we define a lambda expression lengthFunction that implements the StringLengthFunction interface and calculates the length of a string.

We then create an instance of the StringLengthCalculator class and call its calculate method, passing in the lengthFunction lambda expression and the string s.

The calculate method then calls the calculateLength method on the lengthFunction lambda expression, passing in the string s, and returns the length of the string.

Finally, we print the calculated length to the console.

public class LambdaPassingExample {
public static void main(String[] args) {
// define the input string
String s = "Hello, world!";
// define a lambda expression that calculates the length of a string
StringLengthFunction lengthFunction = str -> str.length();
// create an instance of the StringLengthCalculator class
StringLengthCalculator calculator = new StringLengthCalculator();
// call the calculate method, passing in the lambda expression and the input string
int length = calculator.calculate(s, lengthFunction);
// print the calculated length to the console
System.out.println("Length of \"" + s + "\": " + length);
}
}

// define a functional interface that takes in a string and returns an integer
interface StringLengthFunction {
int calculateLength(String str);
}

// define a class that uses the StringLengthFunction interface to calculate the length of a string
class StringLengthCalculator {
public int calculate(String str, StringLengthFunction lengthFunction) {
// call the calculateLength method on the lambda expression, passing in the input string
return lengthFunction.calculateLength(str);
}
}

Alternatively , you can directly pass the directly without creating a reference.

public class LambdaPassingExample {
public static void main(String[] args) {
// define the input string
String s = "Hello, world!";
// create an instance of the StringLengthCalculator class
StringLengthCalculator calculator = new StringLengthCalculator();
// call the calculate method, passing in the lambda expression directly
int length = calculator.calculate(s, str -> str.length());
// print the calculated length to the console
System.out.println("Length of \"" + s + "\": " + length);
}
}

No responses yet