All topics
library
intermediate

Functional Interfaces & @FunctionalInterface

Understand the core functional interfaces (Predicate, Function, Consumer, Supplier) and create custom ones.

A functional interface has exactly one abstract method (SAM — Single Abstract Method). It can be implemented by a lambda or method reference.

Functional interface = a standard electrical outlet shape (the method signature). Lambda = any appliance that fits the outlet. Predicate is a 'yes/no' outlet, Function is a 'convert' outlet, Consumer is a 'use up' outlet.

Key Concepts

1
@FunctionalInterface: optional annotation that makes the compiler enforce the single-abstract-method rule.
2
Core functional interfaces (java.util.function):
3
- Predicate<T>: T → boolean. test(T). For filtering. - Function<T, R>: T → R. apply(T). For transforming. - Consumer<T>: T → void. accept(T). For side effects. - Supplier<T>: () → T. get(). For lazy creation. - UnaryOperator<T>: T → T (special Function). For same-type transforms. - BinaryOperator<T>: (T, T) → T. For combining. - BiFunction<T, U, R>: (T, U) → R. For two-arg transforms. - BiPredicate<T, U>: (T, U) → boolean. For two-arg tests.
4
Composition methods: - Predicate: and(), or(), negate() - Function: compose(), andThen() - Consumer: andThen()
5
Primitive specializations avoid boxing: IntPredicate, LongFunction, DoubleConsumer, ToIntFunction<T>, etc.
6
Practical: you rarely need to create custom functional interfaces — the JDK provides covers most signatures.