Functional interface
A functional interface is an interface with exactly one abstract method (SAM — Single Abstract Method). It can be implemented with a lambda expression or method reference, not just an anonymous class. The marker annotation @FunctionalInterface makes this intent explicit.
Example
@FunctionalInterface
public interface Transformer<T, R> {
R transform(T input);
}
Transformer<String, Integer> length = s -> s.length();
int n = length.transform("Hello"); // 5
Common functional interfaces from java.util.function
| Interface | Method | Use |
|---|---|---|
Function<T, R> | R apply(T) | Transform a value |
Predicate<T> | boolean test(T) | Filter condition |
Consumer<T> | void accept(T) | Side-effect action |
Supplier<T> | T get() | Produce a value |
UnaryOperator<T> | T apply(T) | Same-type transform |
BiFunction<T, U, R> | R apply(T, U) | Two-input function |
Default methods allowed
A functional interface can have any number of default or static methods — only the abstract method count matters. That is why Comparator is a functional interface despite having many default methods like reversed() and thenComparing().