What is a functional interface, and how do you use one without writing a class for it?
A functional interface is an interface with exactly one abstract method. Everything else in it may be default or static, but the single abstract method is what makes it usable as the target of a lambda expression or a method reference.
public class Main {
public static void main(String[] args) {
java.util.function.Function<String, Integer> len = s -> s.length();
java.util.function.Predicate<String> longWord = s -> s.length() > 2;
System.out.println(len.apply("hello"));
System.out.println(longWord.test("hi"));
run(() -> System.out.println("done"));
}
static void run(Runnable task) { task.run(); }
}The example shows the three things you can do. The length function is written as a lambda, an expression that takes a string and returns its length. The predicate is a lambda that answers a yes or no question, and it returns false for a two-letter word. The Runnable is passed as a block of behaviour to a method that knows only the contract, and the output shows the task running.
Because the interface declares the types, the lambda does not need annotations or a return type in most cases. The compiler infers the parameter types and the return type from the target, which is why a lambda can only be used where a functional interface is expected.
The standard library supplies the ones you will use constantly, such as the function type that takes a value and returns a value, the predicate that takes a value and returns a boolean, the supplier that produces a value, the consumer that accepts a value, and the runnable that takes nothing. In practice you rarely declare your own.