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 annotati
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 custom functional interface by annotating it with the @FunctionalInterface annotation.
Here's an example of how to define a custom functional interface and pass it as a parameter:
@FunctionalInterface
interface Action {
void execute();
}
public class Main {
public static void main(String[] args) {
// Create an action that prints "Hello, World!"
Action sayHello = () -> System.out.println("Hello, World!");
// Pass the action as a parameter to the runAction() method
runAction(sayHello);
}
public static void runAction(Action action) {
action.execute();
}
}In this example, the Action interface is a custom functional interface with a single abstract method execute(). The runAction() method accepts an Action parameter and invokes execute() when called.
For most use cases, Java provides built-in functional interfaces in the java.util.function package, such as Consumer<T>, Supplier<T>, and Function<T, R>. These eliminate the need to define custom interfaces. You can pass functions using lambda expressions or method references, which provide a concise and idiomatic way to implement functional interfaces in Java.