Functional Interfaces
Understand Functional Interfaces and their role in Lambda Expressions.
Functional Interfaces
A Functional Interface is an interface that contains exactly one abstract method. They can have any number of default or static methods. Functional interfaces are the basis for Lambda Expressions in Java.
The @FunctionalInterface Annotation
While not mandatory, it is best practice to use the @FunctionalInterface annotation. This ensures the compiler checks that the interface has only one abstract method.
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}Built-in Functional Interfaces
Java 8 introduced the java.util.function package containing common functional interfaces:
Predicate<T>: Takes an argument and returns a boolean.Consumer<T>: Takes an argument and returns nothing (void).Function<T, R>: Takes an argument of type T and returns a result of type R.Supplier<T>: Takes no arguments and returns a result of type T.
Tip 💡
You don't always need to create your own functional interfaces. Check
java.util.function first!
Examples
1. Predicate (Boolean check)
Predicate<String> isLong = s -> s.length() > 5;
System.out.println(isLong.test("Hello World")); // true2. Consumer (Action)
Consumer<String> printer = s -> System.out.println(s);
printer.accept("Java is fun");3. Function (Transformation)
Function<Integer, String> converter = num -> "Number: " + num;
System.out.println(converter.apply(10)); // "Number: 10"4. Supplier (Factory)
Supplier<Double> random = () -> Math.random();
System.out.println(random.get());