What is a functional interface in Java and which built-in ones should you know?
A functional interface has exactly one abstract method, so a lambda can implement it. Core ones are Predicate (test), Function (apply), Consumer (accept) and Supplier (get). @FunctionalInterface makes the compiler check the rule.
Explain it simply
A functional interface is a job with one clearly named task. "Predicate" is a bouncer who answers yes or no. "Function" is a converter. "Consumer" takes something and returns nothing. "Supplier" gives you something without asking for input.
Example
import java.util.function.*;
Predicate<Integer> isAdult = age -> age >= 18;
Function<String, Integer> length = s -> s.length();
Consumer<String> shout = s -> System.out.println(s.toUpperCase());
Supplier<Double> pi = () -> 3.14;
System.out.println(isAdult.test(20)); // prints: true
System.out.println(length.apply("Pune")); // prints: 4
shout.accept("ok"); // prints: OK
System.out.println(pi.get()); // prints: 3.14What to say in the interview
"A functional interface has one abstract method; it may still have default and static methods, and it may re-declare Object methods like equals. The annotation @FunctionalInterface is optional but makes the compiler reject a second abstract method. The standard four are Predicate<T> returning boolean, Function<T,R> transforming, Consumer<T> returning void, and Supplier<T> producing a value. There are also Bi- versions for two arguments and primitive versions like IntPredicate to avoid boxing."
Common mistakes
- Adding a second abstract method and wondering why lambdas stop compiling.