library
intermediateLambda Expressions
Write concise function literals and understand how they relate to functional interfaces, closures, and anonymous classes.
Lambda expressions (Java 8+) are concise syntax for implementing functional interfaces — interfaces with exactly one abstract method. They replace verbose anonymous inner classes for functional-style programming.
Lambda = a sticky note with a quick instruction ('add these two numbers'). Anonymous class = a full letter with letterhead, signature, and envelope for the same instruction.
Key Concepts
1
Syntax: (parameters) -> expression or (parameters) -> { statements; }
- No parameters: () -> System.out.println("hello")
- One parameter: x -> x * 2 (parentheses optional)
- Multiple: (a, b) -> a + b
- With types: (int a, int b) -> a + b
- Multi-line: (a, b) -> { int sum = a + b; return sum; }
2
Lambdas vs anonymous classes:
- Lambdas are more concise and don't create a new .class file per use
- this inside a lambda refers to the enclosing class (not the lambda itself)
- Lambdas can only implement functional interfaces (one abstract method)
- Anonymous classes can extend classes and implement multiple methods
3
Capture rules: lambdas can access effectively final local variables, instance fields, and static fields. They cannot modify local variables (must be effectively final). Instance and static fields can be read and modified.
4
Under the hood: lambdas are NOT anonymous inner classes. The compiler uses invokedynamic and LambdaMetafactory to generate the implementation at runtime. This is more efficient — no extra .class file, potential for JIT optimization.