What is a functional interface in Java?

A functional interface has one abstract method (it can have default and static methods too). The annotation @FunctionalInterface asks the compiler to check this rule.

import java.util.function.Function;
import java.util.function.Predicate;

@FunctionalInterface
interface Validator {
    boolean validate(String text);
}

public class Main {
    public static void main(String[] args) {
        Validator notEmpty = t -> !t.isBlank();
        Predicate<Integer> positive = n -> n > 0;
        Function<String, Integer> length = String::length;

        System.out.println(notEmpty.validate("hi") + " " + notEmpty.validate("  "));
        System.out.println(positive.test(-5));
        System.out.println(length.apply("functional"));
    }
}
Output

true false
false
10

See Java Lambda Expressions.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.