Let’s dive in:
✅ What is a Functional Interface?
A functional interface is an interface that has exactly one abstract method (but can have default or static methods too).
It’s the backbone of lambda expressions and method references in Java.
✅ Why is it called “functional”?
Because it represents a single functionality — like a function!
You can think of it as Java’s version of a function type (like () => int
in JavaScript or (int) -> String
in Kotlin).
✅ How do you define one?
You can use the @FunctionalInterface
annotation (optional, but helpful):
@FunctionalInterface
public interface MyPrinter {
void print(String message);
}
This allows you to write:
MyPrinter printer = msg -> System.out.println(">> " + msg);
printer.print("Hello, Stanley!");
✅ Built-in functional interfaces (in java.util.function
):
Interface | Abstract Method | Description | Example |
---|---|---|---|
Function<T,R> | R apply(T t) | Takes T, returns R | x -> x.length() |
Consumer<T> | void accept(T t) | Takes T, returns nothing | x -> System.out.println(x) |
Supplier<T> | T get() | Takes nothing, returns T | () -> new Random().nextInt() |
Predicate<T> | boolean test(T t) | Takes T, returns boolean | x -> x > 10 |
UnaryOperator<T> | T apply(T t) | Function with same input/output type | x -> x * 2 |
BinaryOperator<T> | T apply(T t1, T t2) | Two inputs, one output (same type) | (a, b) -> a + b |
✅ Example with built-in interface:
Predicate<String> isShort = s -> s.length() < 5;
System.out.println(isShort.test("Stan")); // true
🧠 TL;DR
- Functional interfaces have one abstract method.
- Enable use of lambda expressions and method references.
- Java provides many in
java.util.function
, but you can also make your own.