π§© What is a Functional Interface?
AΒ Functional Interface is an interface in Java that contains exactly one abstract method.
β It can have default and static methods, but only one abstract method.
They are the foundation of Lambda Expressions.
π Declaration Example
You can use a lambda expression with it:
π‘ The
@FunctionalInterface
annotation is optional, but it helps catch errors.
π¦ Common Built-in Functional Interfaces (from java.util.function
)
Interface | Abstract Method | Use Case | Example |
---|---|---|---|
Predicate<T> |
boolean test(T t) |
Condition checking / filtering | x -> x > 10 |
Function<T, R> |
R apply(T t) |
Transformation / mapping | x -> x.toString() |
Consumer<T> |
void accept(T t) |
Consumes input (no return) | x -> System.out.println(x) |
Supplier<T> |
T get() |
Supplies result (no input) | () -> "Hello" |
UnaryOperator<T> |
T apply(T t) |
Unary operations (e.g., square) | x -> x * x |
BinaryOperator<T> |
T apply(T t1, T t2) |
Binary operations (e.g., sum) | (a, b) -> a + b |
π§ Custom Functional Interface Example
π Functional Interfaces + Streams
β Summary
Feature | Description |
---|---|
Abstract Method Count | Only 1 |
Annotation |
@FunctionalInterface (optional) |
Lambda Compatibility | Yes |
Use in Java API | Stream API, Threads, Event handling |