Functional Interfaces in Java
A functional interface in Java is an interface that contains exactly one abstract method. This single abstract method (SAM) is the method that a lambda exp...
The Building Blocks of Functional Java
A functional interface in Java is an interface that contains exactly one abstract method. This single abstract method (SAM) is the method that a lambda expression or method reference implements. Functional interfaces may have multiple default or static methods, but only one abstract method. The @FunctionalInterface annotation is optional but recommended; it makes the compiler enforce the single abstract method constraint.
Java 8 introduced the java.util.function package containing a rich set of built-in functional interfaces designed to cover the most common use cases. The four most important are:
Predicate<T>: takes an argument of type T and returns boolean. Used for filtering. Example: Predicate<String> isEmpty = String::isEmpty;
Function<T, R>: takes T and returns R. Used for transformations. Example: Function<String, Integer> length = String::length;
Consumer<T>: takes T and returns nothing. Used for side effects. Example: Consumer<String> print = System.out::println;
Supplier<T>: takes no arguments and returns T. Used for lazy evaluation. Example: Supplier<List<String>> listFactory = ArrayList::new;
Predicate<Integer> isEven = n -> n % 2 == 0; List<Integer> numbers = List.of(1, 2, 3, 4, 5); numbers.stream().filter(isEven).forEach(System.out::println); // 2, 4
Functional interfaces also compose well. Predicate has andThen() and negate() methods. Function has andThen() and compose() to chain transformations. This composability allows you to build complex logic from simple, testable units.
BiFunction<T, U, R> handles two input arguments. UnaryOperator<T> is a specialization of Function where input and output types are the same. BinaryOperator<T> handles two inputs of the same type and returns the same type.
Interview tip: Interviewers often ask why @FunctionalInterface is needed if Java can infer it automatically. The annotation acts as a safety net: if someone accidentally adds a second abstract method to the interface, the compiler immediately reports an error, preventing subtle runtime breakage.