Lambda Expressions in Java 8
A lambda expression in Java is a short, anonymous function that you can pass around like a value. It was added in Java 8 (JEP 126) and gives you a compact way to implement an interface that has exactly one abstract method, such as Comparator or Runnable.
This tutorial explains the problem lambdas solve, the syntax rules, how they capture variables, and the mistakes interviewers like to ask about. Every example compiles with --release 8.
1. Why Were Lambda Expressions Added?
Before Java 8, passing behaviour to a method meant writing an anonymous inner class. Sorting a list by a custom rule took five or six lines of boilerplate for one line of real logic. This made APIs that accept behaviour, such as event handlers and comparators, awkward to use.
Lambdas remove that boilerplate. They also made the new Stream API practical, because operations like filter and map take small functions as arguments. The result is code that states what should happen rather than how to wire it up.
2. Lambda Expression Syntax
A lambda has a parameter list, the arrow token ->, and a body:
(parameters) -> expression
(parameters) -> { statements; return value; }
// examples
() -> System.out.println("hi") // no parameters
name -> name.length() // one parameter, parentheses optional
(a, b) -> a + b // types inferred from the target
(String a, String b) -> a.compareTo(b) // explicit types
- Parameter types are usually inferred from the target interface, so you rarely write them.
- An expression body returns its value automatically; a block body in braces needs an explicit
return. - A lambda has no name and no class of its own: its type comes from the functional interface it is assigned to.
3. Practical Examples
Example 1: Replacing an anonymous class
The program sorts the same list three times: with an anonymous class, with a one-line lambda, and with a block-body lambda that sorts by length and then alphabetically.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class LambdaBasics {
public static void main(String[] args) {
List<String> cities = new ArrayList<>(Arrays.asList("Pune", "Delhi", "Kochi", "Agra"));
// Before Java 8: an anonymous class just to pass one method
Collections.sort(cities, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.compareTo(b);
}
});
System.out.println("Anonymous class : " + cities);
// Java 8: the same behaviour as a lambda expression
cities.sort((a, b) -> b.compareTo(a));
System.out.println("Lambda (reverse): " + cities);
// A lambda with a block body and an explicit return
Comparator<String> byLengthThenName = (a, b) -> {
int diff = a.length() - b.length();
return diff != 0 ? diff : a.compareTo(b);
};
cities.sort(byLengthThenName);
System.out.println("Block body : " + cities);
// forEach with a lambda instead of a loop
cities.forEach(c -> System.out.println(" visit " + c));
}
}
Anonymous class : [Agra, Delhi, Kochi, Pune] Lambda (reverse): [Pune, Kochi, Delhi, Agra] Block body : [Agra, Pune, Delhi, Kochi] visit Agra visit Pune visit Delhi visit Kochi
cities.sort(...) accepts a Comparator, so the compiler knows a and b are strings. The block body is useful when the logic needs more than one statement.
Example 2: Capturing variables
A lambda can read local variables from the enclosing method, but only if they are final or effectively final, meaning they are never reassigned after initialisation.
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class EffectivelyFinal {
public static void main(String[] args) {
int minimumAge = 18; // never reassigned, so "effectively final"
// The lambda captures minimumAge from the enclosing method
Predicate<Integer> isAdult = age -> age >= minimumAge;
List<Integer> ages = Arrays.asList(12, 18, 25, 16, 40);
for (int age : ages) {
System.out.println(age + " -> " + (isAdult.test(age) ? "adult" : "minor"));
}
// minimumAge = 21; // would not compile: variables used in a lambda
// // must be final or effectively final
// Runnable with no parameters
Runnable greet = () -> System.out.println("Checked " + ages.size() + " ages");
greet.run();
}
}
12 -> minor 18 -> adult 25 -> adult 16 -> minor 40 -> adult Checked 5 ages
Uncommenting minimumAge = 21; causes a compile error, because the lambda captured the value of minimumAge. Instance fields and static fields do not have this restriction.
4. How a Lambda Is Matched to an Interface
The compiler converts a lambda into an instance of the target type: the functional interface expected at that position. The parameter count, parameter types and return type must fit that interface's single abstract method.
At run time the JVM creates the implementation with invokedynamic instead of generating a separate .class file for every lambda, which keeps start-up and memory costs low.
5. Before and After Java 8
| Task | Before Java 8 | Java 8 lambda |
|---|---|---|
| Run a task | new Runnable() { public void run() { ... } } | () -> work() |
| Sort strings by length | Anonymous Comparator class | (a, b) -> a.length() - b.length() |
| Loop and print | for (String s : list) { ... } | list.forEach(s -> System.out.println(s)) |
6. Important Points and Best Practices
- A lambda can only be used where a functional interface is expected.
thisinside a lambda refers to the enclosing instance, unlike in an anonymous class, where it refers to the anonymous object.- Keep lambdas short. If the body grows beyond a few lines, move it to a named method and use a method reference.
- Lambdas cannot throw checked exceptions unless the functional interface method declares them, which is why
Functioncannot call a method that throwsIOExceptiondirectly. - Avoid side effects such as modifying shared lists from inside stream lambdas; it makes code hard to reason about and unsafe in parallel streams.
7. Summary
- A lambda is a short anonymous function introduced in Java 8 by JEP 126.
- It implements a functional interface: an interface with exactly one abstract method.
- Syntax:
(parameters) -> expressionor a block body withreturn. - Captured local variables must be final or effectively final.
- Lambdas replace most anonymous classes and power the Stream API.
Related Tutorials
8. References
Frequently Asked Questions (FAQ)
Q1. What is a lambda expression in Java?
A lambda expression is an anonymous function introduced in Java 8. It provides the implementation of the single abstract method of a functional interface, such as Comparator or Runnable, in a compact form.
Q2. What does effectively final mean?
A local variable is effectively final if it is never reassigned after it is initialised. Lambdas and anonymous classes may only capture such variables, because they capture the value, not the variable itself.
Q3. What is the difference between a lambda and an anonymous class?
A lambda can implement only functional interfaces, has no state of its own, and this refers to the enclosing object. An anonymous class can implement any interface or extend a class, can have fields, and this refers to the anonymous object.
Q4. Can a lambda expression throw a checked exception?
Only if the abstract method of the target functional interface declares that exception. Standard interfaces such as Function and Consumer do not, so checked exceptions must be caught inside the lambda or wrapped.