What are lambda expressions, and how do they relate to functional interfaces?
Quick Answer
A lambda expression is a concise, anonymous block of code — parameters plus a body — that can be passed around as a value. It only compiles where the target type is a functional interface (an interface with exactly one abstract method), since the lambda supplies the implementation of that single method. This lets you pass behavior as an argument without the boilerplate of an anonymous class.
Detailed Answer
A lambda expression is a compact way to write an implementation of a single-method interface inline, without the ceremony of a named class or anonymous class:
Runnable r = () -> System.out.println("running");
Comparator<String> byLength = (a, b) -> a.length() - b.length();
Lambdas only type-check against a functional interface — an interface with exactly one abstract method (it may have any number of default/static methods, which don't count). The lambda's parameter list and body supply the implementation of that one abstract method; the compiler infers everything else from the target type context.
@FunctionalInterface
interface Calculator {
int operate(int a, int b);
}
Calculator add = (a, b) -> a + b;
add.operate(3, 4); // 7
The @FunctionalInterface annotation isn't required, but documents intent and causes a compile error if a second abstract method is later added by mistake, protecting the lambda-compatibility contract.
Compared to an equivalent anonymous class, a lambda is more concise, doesn't create an extra .class file for each usage (implemented instead via invokedynamic and method handles under the hood), and — unlike an anonymous class — does not introduce its own this (a lambda's this refers to the enclosing instance, not the lambda itself).
Lambdas underpin the entire Java 8 functional style: the java.util.function package, the Stream API, and countless JDK APIs (Comparator.comparing, list.forEach, map.computeIfAbsent) all accept functional-interface parameters designed to be filled with lambdas.