Lambda
Expressions
Master the art of writing concise, expressive code using Java's lambda syntax: anonymous functions that bring functional programming to your toolkit.
What Is a Lambda Expression?
A lambda expression is a short block of code that takes parameters and returns a value. Think of it as an anonymous function: a method without a name that you can pass around like a variable.
Why Do Lambdas Matter?
Before Java 8, passing behavior required creating an entire anonymous inner class. Lambdas let you express the same idea in far fewer lines, making your code easier to read and maintain.
Functional Interfaces: The Foundation
A lambda expression can only be used where Java expects a functional interface: an interface with exactly one abstract method. The lambda provides the implementation of that method.
Anatomy of a Lambda
->: separates parameters from the body.Syntax Variations
() -> 42Empty parens required
x -> x * 2Parens optional for one param
(a, b) -> a + bParens required, comma-separated
(x) -> { return x * x; }Braces + explicit return
(int a, int b) -> a + bExplicit type declarations
Lambda vs Anonymous Class
| Lambda Expression | Anonymous Inner Class | |
|---|---|---|
| Syntax | Concise: 1-2 lines | Verbose: 5+ lines |
| Target | Functional interfaces only | Any interface or abstract class |
this keyword |
Refers to enclosing class | Refers to the inner class itself |
| Compiled as | invokedynamic | Separate .class file |
| Performance | Faster (less overhead) | Slower (class loading) |
How to Write a Lambda
-> after the parameters.Example 1: Sorting with a Lambda
The Comparator interface has one abstract method: compare(T a, T b). This makes it a perfect target for a lambda.
Example 2: Iterating with forEach
The forEach method accepts a Consumer<T>: a functional interface whose abstract method accept(T t) takes one parameter and returns nothing.
Example 3: Filtering with Predicate
Predicate<T> has one abstract method: test(T t), which returns a boolean. It is the go-to interface for filter conditions.
Java's Built-in Functional Interfaces
| Interface | Abstract Method | Use Case |
|---|---|---|
| Predicate<T> | test(T) -> boolean |
Filtering, conditions |
| Function<T,R> | apply(T) -> R |
Transformations, mapping |
| Consumer<T> | accept(T) -> void |
forEach, side effects |
| Supplier<T> | get() -> T |
Lazy generation, factories |
| Comparator<T> | compare(T,T) -> int |
Sorting, ordering |
Block Body: Multiple Statements
When the lambda body needs more than one statement, wrap it in curly braces. If the interface method has a return type, you must include an explicit return statement.
Variable Capture
Lambdas can capture variables from the surrounding scope, but those variables must be effectively final: assigned once and never modified after.
Common Mistakes
{ } but forgetting the return keyword. The compiler expects a return if the method has a non-void return type.Lambda Quick Reference
| Pattern | Syntax | Example |
|---|---|---|
| No params | () -> expr |
() -> 42 |
| One param | x -> expr |
x -> x * 2 |
| Two params | (a, b) -> expr |
(a, b) -> a + b |
| Block body | (x) -> { ... } |
(x) -> { return x; } |
| With types | (T x) -> expr |
(int x) -> x + 1 |
Question 1 of 5
Which of the following is the correct lambda expression for a Comparator<String> that compares strings by length?
Question 2 of 5
A functional interface in Java is an interface that has:
Question 3 of 5
What does the following code print?
List<Integer> nums = List.of(1, 2, 3);
nums.forEach(n -> System.out.print(n * 3 + " "));
n -> System.out.print(n * 3 + " ") multiplies each element by 3 and prints it with a space. For the list [1, 2, 3], the output is 3 6 9.Question 4 of 5
Which lambda syntax is invalid in Java?
Question 5 of 5
Why does the following code fail to compile?
int count = 0;
List<String> names = List.of("A", "B", "C");
names.forEach(name -> count++);