🧩 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

@FunctionalInterface
interface MyFunctionalInterface {
Β  Β  void doSomething();
}
Β 

You can use a lambda expression with it:

MyFunctionalInterface action = () -> System.out.println("Doing something!");
action.doSomething();

πŸ’‘ 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

@FunctionalInterface
interface Calculator {
Β  Β  int compute(int a, int b);
}

Calculator add = (x, y) -> x + y;
System.out.println(add.compute(5, 3)); // 8


πŸ”„ Functional Interfaces + Streams

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

// Predicate + Consumer in action
numbers.stream()
Β  Β  Β  Β .filter(n -> n % 2 == 0)
Β  Β  Β  Β .forEach(n -> System.out.println("Even: " + n));


βœ… Summary

Feature Description
Abstract Method Count Only 1
Annotation @FunctionalInterface (optional)
Lambda Compatibility Yes
Use in Java API Stream API, Threads, Event handling
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.