Functional Interfaces
A Functional Interface is an interface with exactly one abstract method. It forms the foundation for lambda expressions in Java.
Declaration
@FunctionalInterface
interface MyFunctionalInterface {
void execute();
}
- The
@FunctionalInterface
annotation is optional but recommended. - Having more than one abstract method will result in a compilation error if the annotation is present.
Example with Lambda
public class Main {
public static void main(String[] args) {
MyFunctionalInterface f = () -> System.out.println("Executed!");
f.execute();
}
}
Built-in Functional Interfaces (in java.util.function
)
Predicate<T>
โ returns booleanFunction<T, R>
โ returns a valueConsumer<T>
โ performs an actionSupplier<T>
โ provides a value
Predicate<String> isLong = s -> s.length() > 5;
System.out.println(isLong.test("Hello")); // false
Benefits
- Enables cleaner, more modular code
- Essential for lambda expressions
- Supports functional programming