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
Learn more about the similar topics:
| Tutorials |
|---|
| Java Lambda Expressions |
| Java Streams API |
| Java Optional |
| Exercises & Assignments |
|---|
| Use streams to filter and sum numbers |
| Interview Questions & Answers |
|---|
| What is the difference between map() and flatMap() in Java streams? |
| What is a functional interface in Java? |