How to pass a function as a parameter in Java?
In Java, you can pass a function as a parameter using a functional interface. A functional interface is an interface that has a single abstract method. You can create a functional interface by annotating an interface with the @FunctionalInterface
annotation.
Here's an example of how you can create a functional interface and pass a function as a parameter in Java:
@FunctionalInterface
interface Function {
void apply();
}
public class Main {
public static void main(String[] args) {
// Create a function that prints "Hello, World!"
Function sayHello = () -> System.out.println("Hello, World!");
// Pass the function as a parameter to the runFunction() method
runFunction(sayHello);
}
public static void runFunction(Function func) {
func.apply();
}
}
In this example, the Function
interface is a functional interface that has a single abstract method called apply()
. The runFunction()
method takes a Function
as a parameter and calls the apply()
method on it when it is called.
I hope this helps! Let me know if you have any questions.