Easy java java-21

What are functional interfaces and lambdas?

The 30 second answer

A functional interface is an interface with exactly one abstract method, like Runnable, Function or Predicate. A lambda is just a short way to write an implementation of that one method, so I can pass behavior around like data. The FunctionalInterface annotation is optional; it only asks the compiler to fail if someone adds a second abstract method.

A functional interface has exactly one abstract method. Default methods, static methods and methods that override Object methods (like equals) don't count. A lambda expression or a method reference can be used wherever such an interface is the target type; the compiler infers the parameter types from that target.

Predicate<String> isEmpty = s -> s.isEmpty();
Function<String, Integer> len = String::length;   // method reference
Runnable task = () -> System.out.println("run");

@FunctionalInterface is optional. It documents intent and makes the compiler reject the interface if it stops having exactly one abstract method. The standard shapes live in java.util.function: Function, Supplier, Consumer, Predicate, BiFunction, UnaryOperator, plus primitive versions like IntPredicate that avoid boxing.

Lambdas can use local variables from the enclosing scope only if those variables are final or effectively final.

Follow-up: Can a functional interface have default methods? Yes, any number; only abstract methods count.

Sources: JLS 9.8 Functional Interfaces, JLS 15.27 Lambda Expressions, java.util.function

Sources (0)
See inline citations in the answer above.