Lambdas: the syntax that started it
See an anonymous class collapse into a lambda, and understand what the compiler actually does.
Open this lesson in the learning hubKey points
- A lambda is not "an anonymous class with less typing" - it compiles to an
invokedynamiccall site, not a new class file. - It only works where the target type is an interface with one abstract method.
- The parameter types are inferred from that target type, which is why
(a, b) -> a - bneeds no declarations. thisinside a lambda means the enclosing object - in an anonymous class it meant the anonymous instance.- A non-capturing lambda can be reused as a single instance, so it is often cheaper than the class it replaced.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Charlie", "ada", "Bob"));
// Java 7 style
names.sort(new Comparator<String>() {
@Override public int compare(String a, String b) {
return a.compareToIgnoreCase(b);
}
});
System.out.println("anonymous class : " + names);
// Java 8 style - same behaviour, one line
names.sort((a, b) -> a.compareToIgnoreCase(b));
System.out.println("lambda : " + names);
// 'this' differs: a lambda sees the enclosing instance
Runnable r = () -> System.out.println("lambdas are not inner classes");
r.run();
}
}
A lambda is a target-typed function, linked at runtime - not sugar for an inner class.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 8 Course course, and every lesson in it is listed on the Java 8 Course contents page.