Junior
What is a functional interface?
sobes.tech AI
Answer from AI
A functional interface is an interface that contains exactly one abstract method. It may contain default and static methods. It is used for working with lambda expressions and method references.
The @FunctionalInterface annotation is not mandatory but is recommended for explicit identification and for the compiler to verify whether the interface meets the definition of a functional interface. If an interface is annotated with it but contains more or less than one abstract method, the compiler will generate an error.
Examples of standard functional interfaces from the java.util.function package:
Predicate<T>: Accepts an argument of typeTand returns aboolean. One abstract method:boolean test(T t);.Consumer<T>: Accepts an argument of typeTand returns nothing (void). One abstract method:void accept(T t);.Supplier<T>: Takes no arguments and returns a value of typeT. One abstract method:T get();.Function<T, R>: Accepts an argument of typeTand returns a value of typeR. One abstract method:R apply(T t);.
An example of a user-defined functional interface:
@FunctionalInterface
interface StringProcessor {
String process(String input); // The only abstract method
// Additionally, default or static methods can be added
default String toUpperCase(String input) {
return input.toUpperCase();
}
}
Example of usage with a lambda expression:
StringProcessor processor = s -> s + " processed";
String result = processor.process("hello"); // "hello processed"