Lambda Expressions
A lambda is a short way to write an object that implements a single-method interface, so behavior can be passed around like data. This page shows every syntax form, how the compiler decides a lambda's type, which variables a lambda may use, why its body runs later or never, the collection methods built around lambdas, and the limits that need workarounds.
Contents
What a lambda expression is
A lambda expression is a short way to write an object that implements an interface with a single abstract method, called a functional interface. Instead of declaring a class, naming a method and creating an instance, you write only the parameters and the body: (a, b) -> a + b
Lambdas arrived in Java 8 together with method references and the java.util.functionComparatorMap.computeIfAbsentCompletableFuture
| Form | Example | Since | Best for |
|---|---|---|---|
| Named class | class ByLength implements Comparator<String> | 1.0 | Logic that is reused, tested on its own or has state |
| Anonymous class | new Comparator<>() { ... } | 1.1 | Interfaces with several methods, or code needing its own this |
| Lambda expression | (a, b) -> a.length() - b.length() | 8 | Short logic written at the place it is used |
| Method reference | String::length | 8 | A lambda that only calls one existing method |
Lambda with var | (var s, var n) -> s.repeat(n) | 11 | Adding annotations to inferred parameter types |
This page covers the language side: syntax, how the compiler picks the type, which variables a lambda can use, and when its body runs. The standard interfaces, composition, method reference kinds and checked exceptions are covered in
Syntax, from anonymous class to lambda
The program sorts the same list with an anonymous class, a lambda and a method reference, then shows every legal form of the parameter list and body. Each line prints a result that is easy to check by hand.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.Supplier;
public class LambdaSyntax {
public static void main(String[] args) {
// The same comparator three ways
Comparator<String> anonymous = new Comparator<>() {
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
};
Comparator<String> lambda = (a, b) -> Integer.compare(a.length(), b.length());
Comparator<String> reference = Comparator.comparingInt(String::length);
List<String> words = new ArrayList<>(List.of("banana", "fig", "apple"));
words.sort(anonymous);
System.out.println("anonymous class: " + words);
words.sort(lambda.reversed());
System.out.println("lambda reversed: " + words);
words.sort(reference);
System.out.println("method reference: " + words);
// Every legal shape of the parameter list and the body
Supplier<String> none = () -> "no parameters";
Function<String, Integer> one = s -> s.length(); // parentheses optional
BiFunction<String, String, String> two = (a, b) -> a + b;
IntBinaryOperator typed = (int a, int b) -> a * b; // explicit types
BiFunction<String, Integer, String> withVar = (var s, var n) -> s.repeat(n); // Java 11
Function<Integer, String> block = n -> {
String sign = n < 0 ? "negative" : "non-negative";
return n + " is " + sign; // block body needs return
};
System.out.println(none.get());
System.out.println("one(\"lambda\") = " + one.apply("lambda"));
System.out.println("two(\"ab\", \"cd\") = " + two.apply("ab", "cd"));
System.out.println("typed(6, 7) = " + typed.applyAsInt(6, 7));
System.out.println("withVar(\"ha\", 3) = " + withVar.apply("ha", 3));
System.out.println(block.apply(-5));
}
}
Output:
anonymous class: [fig, apple, banana]
lambda reversed: [banana, apple, fig]
method reference: [fig, apple, banana]
no parameters
one("lambda") = 6
two("ab", "cd") = abcd
typed(6, 7) = 42
withVar("ha", 3) = hahaha
-5 is negative
- The anonymous class and the method reference produced the same order, [fig, apple, banana], by length. The lambda version was reversed with
, a default method onreversed() , which works because a lambda is a real object of that interface.Comparator - A single parameter needs no parentheses, as in
. Zero parameters or two or more need them, as ins -> s.length() and() -> "no parameters" .(a, b) -> a + b - Parameter types are usually inferred. You can write them, as in
, but then every parameter needs one; mixing typed and untyped parameters does not compile.(int a, int b) - The
form from Java 11 still infers the types. Its purpose is to allow annotations such as(var s, var n) , which need a type position to attach to.(@NonNull var s) - An expression body returns its value automatically. A block body in braces, like the one that printed "-5 is negative", needs an explicit
when the interface method returns a value.return
Target typing and overloads
A lambda has no type of its own. The compiler gives it the type of its target: the variable it is assigned to, the parameter it is passed to, or a cast. The program assigns identical lambda text to different interfaces and then calls an overloaded method to see which version the compiler picks.
import java.util.concurrent.Callable;
import java.util.function.Function;
import java.util.function.IntUnaryOperator;
import java.util.function.Supplier;
public class TargetTyping {
static void run(Runnable r) {
System.out.println(" chose run(Runnable)");
r.run();
}
static void run(Supplier<String> s) {
System.out.println(" chose run(Supplier): " + s.get());
}
public static void main(String[] args) throws Exception {
// One lambda text, three different types: the target decides
Supplier<String> asSupplier = () -> "hello";
Callable<String> asCallable = () -> "hello";
System.out.println("Supplier.get() = " + asSupplier.get()
+ ", Callable.call() = " + asCallable.call());
IntUnaryOperator primitive = x -> x * 2;
Function<Integer, Integer> boxed = x -> x * 2;
System.out.println("IntUnaryOperator: " + primitive.applyAsInt(21)
+ ", Function: " + boxed.apply(21));
// A lambda has no type of its own
// Object o = () -> "x"; does not compile: Object is not a functional interface
// var v = () -> "x"; does not compile: no target type to infer from
Object o = (Supplier<String>) () -> "cast gives it a type";
System.out.println("Object holding a lambda: " + ((Supplier<?>) o).get());
// Overload resolution uses the shape of the body
System.out.println("() -> \"text\":");
run(() -> "text");
System.out.println("() -> System.out.print(\"\"):");
run(() -> System.out.print(""));
System.out.println("() -> { return \"block\"; }:");
run(() -> {
return "block";
});
// A method call fits both shapes: its result can be used or thrown away
System.out.println("() -> \" both \".strip():");
run(() -> " both ".strip());
}
}
Output:
Supplier.get() = hello, Callable.call() = hello
IntUnaryOperator: 42, Function: 42
Object holding a lambda: cast gives it a type
() -> "text":
chose run(Supplier): text
() -> System.out.print(""):
chose run(Runnable)
() -> { return "block"; }:
chose run(Supplier): block
() -> " both ".strip():
chose run(Supplier): both
- The text
became a() -> "hello" in one line and aSupplier in the next. The two objects have unrelated types, so one cannot be assigned to the other even though their lambdas look the same.Callable - The text
printed 42 both times. As anx -> x * 2 it works on a plainIntUnaryOperator ; as aint it unboxes and boxes on every call.Function<Integer, Integer> - Assigning a lambda to
or toObject does not compile, because neither gives the compiler a functional interface to target. A cast such asvar supplies one.(Supplier<String>) - With overloads for
andRunnable , the body decides. A value likeSupplier fits only"text" , andSupplier returns void, so it fits onlySystem.out.print("") .Runnable - The call
fits both, since a method call's result may be used or discarded. The compiler chose" both ".strip() , because JLS 15.12.2.5 prefers the interface whose method returns a value. The same rule makesSupplier pickExecutorService.submit overCallable .Runnable
Captured variables and this
A lambda body can use local variables, parameters and fields from the code around it. The rules differ for locals and fields, and the program shows each case, including the two kinds of loop.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
public class Capture {
private int counter = 0;
private final String name = "Capture object";
Supplier<String> fieldReader() {
return () -> "counter field = " + counter; // really this.counter: captures this
}
Supplier<String> whoIsThis() {
return () -> "this is the " + this.name; // this means the enclosing object
}
public static void main(String[] args) {
// Locals are copied into the lambda, so they must be effectively final
int limit = 10;
IntSupplier readLimit = () -> limit;
// limit = 20; would make the line above fail to compile
System.out.println("captured local limit = " + readLimit.getAsInt());
// Fields are read through 'this', so later changes are visible
Capture c = new Capture();
Supplier<String> f = c.fieldReader();
System.out.println(f.get());
c.counter = 5;
System.out.println(f.get() + " (after the field changed)");
System.out.println(c.whoIsThis().get());
// Loops: the for-each variable is a fresh variable per iteration
List<Supplier<String>> fromForEach = new ArrayList<>();
for (String s : List.of("a", "b", "c")) {
fromForEach.add(() -> s);
}
// A classic for loop variable changes, so copy it first
List<IntSupplier> fromIndex = new ArrayList<>();
for (int i = 0; i < 3; i++) {
int copy = i; // () -> i would not compile
fromIndex.add(() -> copy * 10);
}
StringBuilder out = new StringBuilder("loop captures: ");
fromForEach.forEach(sup -> out.append(sup.get()).append(' '));
fromIndex.forEach(sup -> out.append(sup.getAsInt()).append(' '));
System.out.println(out.toString().strip());
// Counting inside a lambda: change an object's contents, not the variable
AtomicInteger calls = new AtomicInteger();
int[] total = {0};
List.of(3, 4, 5).forEach(n -> {
calls.incrementAndGet();
total[0] += n;
});
System.out.println("calls = " + calls.get() + ", total = " + total[0]);
// A lambda can outlive the method that created it, and keeps its captures
Supplier<String> survivor = makeGreeting("Ada");
System.out.println(survivor.get());
}
static Supplier<String> makeGreeting(String who) {
String greeting = "Hello, " + who; // a local of a method that has returned
return () -> greeting;
}
}
Output:
captured local limit = 10
counter field = 0
counter field = 5 (after the field changed)
this is the Capture object
loop captures: a b c 0 10 20
calls = 3, total = 12
Hello, Ada
- A local variable used in a lambda must be effectively final, meaning it is never assigned again. The value 10 is copied into the lambda object when the lambda is created, so a later
could never be seen, and the compiler rejects it.limit = 20 - Fields have no such rule. The lambda used
, so it printed 0 and then 5 after the field changed. Capturingthis.counter also keeps the whole enclosing object alive as long as the lambda is.this - Inside a lambda,
means the enclosing object, which printed "this is the Capture object". An anonymous class would have its ownthis instead, as covered inthisinner classes . - The for-each loop gave a b c because its variable is a new variable in each iteration. A classic
loop variable changes withfor , soi++ does not compile; copying it to() -> i gave 0, 10 and 20.copy - To change state from inside a lambda, mutate an object instead of the variable. The
counted 3 calls and the one-element array summed to 12. The atomic version is also safe if the lambda runs on several threads.AtomicInteger - The
method had already returned when its lambda printed "Hello, Ada". The captured value lives in the lambda object, not on the finished method's stack.makeGreeting
Deferred execution
Writing a lambda creates an object; it does not run the body. The body runs only when someone calls the interface method, which may be later, many times, or never. The program counts how often an expensive method runs under each approach.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
public class Deferred {
static final AtomicInteger expensiveCalls = new AtomicInteger();
static String expensiveReport() {
expensiveCalls.incrementAndGet();
return "report #" + expensiveCalls.get();
}
static boolean debugEnabled = false;
static void debugEager(String message) {
if (debugEnabled) {
System.out.println("DEBUG " + message);
}
}
static void debugLazy(Supplier<String> message) {
if (debugEnabled) {
System.out.println("DEBUG " + message.get());
}
}
public static void main(String[] args) {
// A lambda is code that runs later, or never
for (int i = 0; i < 1000; i++) {
debugEager(expensiveReport());
}
System.out.println("eager, debug off: " + expensiveCalls.getAndSet(0) + " reports built");
for (int i = 0; i < 1000; i++) {
debugLazy(() -> expensiveReport());
}
System.out.println("lazy, debug off: " + expensiveCalls.getAndSet(0) + " reports built");
// Optional.orElse evaluates its argument even when a value is present
Optional<String> present = Optional.of("cached");
present.orElse(expensiveReport());
System.out.println("orElse on a present value: " + expensiveCalls.getAndSet(0)
+ " call");
present.orElseGet(Deferred::expensiveReport);
System.out.println("orElseGet on a present value: " + expensiveCalls.getAndSet(0)
+ " calls");
// computeIfAbsent runs the lambda only for missing keys
Map<String, Integer> lengths = new HashMap<>();
AtomicInteger computed = new AtomicInteger();
for (String w : List.of("kiwi", "fig", "kiwi", "kiwi", "fig", "plum")) {
lengths.computeIfAbsent(w, k -> {
computed.incrementAndGet();
return k.length();
});
}
System.out.println("6 lookups, " + lengths.size() + " keys, lambda ran "
+ computed.get() + " times");
// Creating a lambda does not run it
Runnable boom = () -> {
throw new IllegalStateException("only when run");
};
System.out.println("lambda created, nothing thrown yet");
try {
boom.run();
} catch (IllegalStateException e) {
System.out.println("run() threw: " + e.getMessage());
}
}
}
Output:
eager, debug off: 1000 reports built
lazy, debug off: 0 reports built
orElse on a present value: 1 call
orElseGet on a present value: 0 calls
6 lookups, 3 keys, lambda ran 3 times
lambda created, nothing thrown yet
run() threw: only when run
- With logging disabled,
still built 1000 reports, because Java evaluates arguments before the call. Passing adebugEager(expensiveReport()) built 0, sinceSupplier was never called. This is whyget() and SLF4J 2 accept suppliers.java.util.logging.Logger - The call
ran the method once even though a value was present. TheOptional.orElse(expensiveReport()) version takes a supplier and ran it 0 times, as explained on theorElseGetOptional page . - Six
lookups over three distinct words ran the lambda 3 times. The map calls it only for a missing key, which makes it a simple cache.computeIfAbsent - Creating the
lambda printed nothing unusual. The exception appeared only atboom , so its stack trace points at the caller ofrun() , not at the line where the lambda was written.run()
Lambdas in the collections API
Many collection methods added in Java 8 take a lambda, so everyday code uses them even without streams. The program sorts records by three keys, edits a list in place and totals a map.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class CollectionLambdas {
record Employee(String name, String dept, int salary) { }
public static void main(String[] args) {
List<Employee> staff = new ArrayList<>(List.of(
new Employee("Mia", "Ops", 70),
new Employee("Ben", "Dev", 90),
new Employee("Ava", "Dev", 90),
new Employee("Leo", "Ops", 55),
new Employee("Zoe", "QA", 65)));
// Sort by department, then highest salary first, then name
staff.sort(Comparator.comparing(Employee::dept)
.thenComparing(Employee::salary, Comparator.reverseOrder())
.thenComparing(Employee::name));
staff.forEach(e -> System.out.println(" " + e.dept() + " " + e.salary() + " " + e.name()));
// removeIf takes a Predicate, replaceAll a UnaryOperator
List<String> names = new ArrayList<>(staff.stream().map(Employee::name).toList());
names.removeIf(n -> n.startsWith("Z"));
names.replaceAll(String::toUpperCase);
System.out.println("removeIf + replaceAll: " + names);
// Map.merge takes a BiFunction that combines old and new values
Map<String, Integer> payroll = new TreeMap<>();
for (Employee e : staff) {
payroll.merge(e.dept(), e.salary(), Integer::sum);
}
System.out.println("payroll by dept: " + payroll);
// Map.forEach passes key and value: a BiConsumer
StringBuilder sb = new StringBuilder();
payroll.forEach((dept, total) -> sb.append(dept).append('=').append(total).append(' '));
System.out.println("Map.forEach: " + sb.toString().strip());
// A Runnable as a task
Thread worker = new Thread(() -> System.out.println("thread says: "
+ Thread.currentThread().getName()), "worker-1");
worker.start();
try {
worker.join();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
Output:
Dev 90 Ava
Dev 90 Ben
Ops 70 Mia
Ops 55 Leo
QA 65 Zoe
removeIf + replaceAll: [AVA, BEN, MIA, LEO]
payroll by dept: {Dev=180, Ops=125, QA=65}
Map.forEach: Dev=180 Ops=125 QA=65
thread says: worker-1
- The comparator sorted by department, then by salary from high to low, then by name. Ava and Ben both earn 90 in Dev, so the third key put Ava first.
- The
method took aremoveIf and removed Zoe;Predicate took areplaceAll and upper-cased the remaining four names in place.UnaryOperator - The
call tookMap.merge as the function that combines an existing value with a new one. It produced Dev=180 and Ops=125 without any "is the key there yet" check.Integer::sum - The
method passes key and value as two lambda parameters, which is shorter than iterating overMap.forEach .entrySet() - The thread ran a
lambda and printed its name, worker-1. Any API that takes aRunnable orRunnable , such as the ones onCallablethread basics , accepts a lambda the same way.
What a lambda cannot do
Lambdas are deliberately limited, and each limit has a standard workaround. The program shows four of them; the lines that do not compile are kept as comments with the compiler's message.
import java.util.List;
import java.util.function.Function;
import java.util.function.IntUnaryOperator;
import java.util.function.UnaryOperator;
public class Limits {
// A lambda cannot name itself in its own local initializer, but a field works
static IntUnaryOperator factorial;
static {
factorial = n -> n <= 1 ? 1 : n * factorial.applyAsInt(n - 1);
}
// A lambda cannot declare type parameters; a generic method can
static <T> List<T> twice(T value) {
return List.of(value, value);
}
interface Doubler {
<T> List<T> apply(T value); // generic method: no lambda can implement this
}
public static void main(String[] args) {
// IntUnaryOperator f = n -> n <= 1 ? 1 : n * f.applyAsInt(n - 1);
// does not compile: "variable f might not have been initialized"
System.out.println("factorial(10) = " + factorial.applyAsInt(10));
// A method reference can target a generic method; the type is fixed per use
Function<String, List<String>> strings = Limits::twice;
Function<Integer, List<Integer>> ints = Limits::twice;
System.out.println(strings.apply("x") + " " + ints.apply(7));
// Doubler d = v -> List.of(v, v); does not compile: the method is generic
Doubler d = Limits::twice; // a method reference is allowed
System.out.println("Doubler via reference: " + d.apply("ok") + " " + d.apply(1.5));
// Lambdas cannot shadow locals of the enclosing method
String s = "outer";
// UnaryOperator<String> bad = s -> s + "!"; does not compile: s is already defined
UnaryOperator<String> good = t -> t + "!";
System.out.println(good.apply(s));
}
}
Output:
factorial(10) = 3628800
[x, x] [7, 7]
Doubler via reference: [ok, ok] [1.5, 1.5]
outer!
- A lambda cannot call itself through the local variable it initializes, because javac reports "variable f might not have been initialized". Storing it in a static field works, and
printed 3628800.factorial(10) - A lambda cannot declare type parameters, so no lambda can implement an interface whose single method is generic, such as
. A method reference to the generic methodDoubler.apply is allowed and worked for both a string and a double.twice - The same reference,
, served as aLimits::twice of strings and of integers. Its type parameter is inferred separately for each target.Function - Lambda parameters share the enclosing scope, so naming one
when a locals exists fails with "variable s is already defined". Rename the parameter.s - The standard interfaces declare no checked exceptions, so a lambda passed to
cannot throw anmap . The usual fix is a wrapping adapter, shown in the checked exceptions section of theIOExceptionfunctional interfaces page .
Choosing a form
| Situation | Prefer | Reason |
|---|---|---|
| One or two lines of logic at the call site | Lambda expression | The behavior is visible where it is used |
| The body only calls an existing method | Method reference such as String::length | Shorter, and the method name documents the intent |
| Logic longer than a few lines | A private method plus a method reference | The method can be named, tested and debugged on its own |
| Interface with more than one abstract method | Anonymous or named class | A lambda can implement only one method |
The object needs its own fields or this | Anonymous or named class | A lambda has no state of its own beyond captures |
| An expensive argument that may not be needed | A Supplier | The body runs only if get() |
| Counting or collecting from inside a lambda | AtomicInteger | Captured locals cannot be reassigned |
A good test is to read the lambda aloud at its call site. If it needs a comment to explain it, a named method with a method reference is usually clearer.