Lambdas
A lambda is a short, nameless function. You write it where a functional interface is expected, and the compiler turns it into an implementation of that interface.
Detailed Explanation
Before Java 8, passing behaviour meant an anonymous class: a Comparator with one compare method and twenty lines of ceremony. A lambda is that method. (a, b) -> a.length() - b.length() is a Comparator<String> when the target type says so.
The shape is (parameters) -> body. One parameter can drop the parentheses. A single-expression body is the return value. A block body needs return and braces. Types on parameters are optional when the compiler can infer them from the target type. The target type is the functional interface you are assigning to, passing to, or returning: exactly one abstract method.
Lambdas capture enclosing locals that are final or effectively final. The capture is a copy of the value (or reference). You cannot assign the local after the lambda is created. this inside a lambda is the enclosing instance, not a hidden lambda object. That is different from an anonymous class.
Lambdas cannot throw checked exceptions unless the functional method declares them. Runnable.run declares none, so a lambda used as Runnable cannot throw IOException without wrapping. They cannot be generic themselves; the interface can be.
You reach for a lambda when the behaviour is short and local: a sort key, a filter, a callback. You reach for a named method or a class when the body has a name, needs tests, or spans many lines. Method references (String::length) are lambdas with even less syntax when an existing method already matches.
The cost is opacity. A stack trace may show lambda$main$0 instead of a method name. Debugging stepping can jump oddly. A lambda that closes over a large enclosing instance keeps that instance alive. Keep lambdas small, and prefer static methods or method references when you do not need instance state.
Code Examples
import java.util.Arrays;
public class SortByLength {
public static void main(String[] args) {
String[] names = {"cy", "ana", "bo"};
Arrays.sort(names, (a, b) -> Integer.compare(a.length(), b.length()));
System.out.println(Arrays.toString(names)); // prints: [cy, bo, ana]
}
}import java.util.function.Predicate;
public class Capture {
static Predicate<String> startsWith(String prefix) {
// prefix is effectively final, so the lambda may read it
return s -> s.startsWith(prefix);
}
public static void main(String[] args) {
System.out.println(startsWith("Ja").test("Java")); // prints: true
System.out.println(startsWith("Ja").test("Go")); // prints: false
}
}Common Gotchas
Captured locals must be effectively final
`count++` in the enclosing method after the lambda is created does not compile if the lambda reads `count`.
Checked exceptions must match the functional method
wrap them in a runtime exception, or use an interface that declares `throws`.
`this` is the enclosing class
to refer to the lambda itself (recursion), assign it to a field first, not a local that is still being declared.
A lambda in an instance method captures `this`
storing that lambda in a cache can pin the outer object.