Java Programming
Lambdas, Method References and Functional Interfaces in Java
Intermediate8 min readUpdated
Lambdas turned Java into a language where behaviour can be passed around as easily as data. This guide explains what a lambda actually is — an instance of a functional interface — how the compiler infers its type, the built-in interfaces in java.util.function, the four kinds of method reference, the rules for capturing variables, and how lambdas are compiled. You will be able to write, read and design APIs around lambdas with confidence.
What you will learn
- Explain how a lambda expression is typed against a functional interface
- Choose the right java.util.function interface, including primitive specialisations
- Convert between lambdas and the four forms of method reference
- Apply the effectively-final rule and know why lambdas cannot mutate captured locals
- Compose functions, predicates and comparators, and design methods that accept behaviour
Java 8 added lambda expressions, and with them a change in how Java code is written: behaviour became a first-class argument. Sorting, filtering, retry policies, event handlers and thread bodies all became one-liners instead of anonymous classes. The syntax is easy; what trips people up is the typing model (a lambda has no type of its own), the capture rules, and the growing catalogue of interfaces in java.util.function. This guide covers those foundations, on which the streams API and much of modern Java depend. Code targets Java 21.
What a lambda is
A lambda expression is a compact way to create an instance of a functional interface — an interface with exactly one abstract method. The lambda's parameters and body become that method's implementation.
// Before: an anonymous class
Comparator<String> byLength = new Comparator<String>() {
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
};
// After: a lambda
Comparator<String> byLength = (a, b) -> Integer.compare(a.length(), b.length());
The shape is parameters -> body. Parameter types are usually inferred; a single parameter needs no parentheses; a body that is one expression needs no braces or return; a block body uses both. var is permitted for parameter types since Java 11, mainly so that you can attach annotations to them.
Runnable hello = () -> System.out.println("hi"); // no parameters
Function<String, Integer> len = s -> s.length(); // one parameter, expression body
BiFunction<Integer, Integer, Integer> add = (Integer a, Integer b) -> { // explicit types, block body
int sum = a + b;
return sum;
};
Target typing
A lambda has no intrinsic type. (a, b) -> a + b could be a BinaryOperator<Integer>, a BiFunction<String, String, String> or a Comparator<Integer> (badly). The compiler determines the target type from context — the variable being assigned, the method parameter, the return type, a cast — and checks the lambda against that interface's single abstract method. This is why you cannot write var f = x -> x + 1; (no target) and why overloaded methods that accept different functional interfaces sometimes need a cast or explicit parameter types to disambiguate.
Any interface with one abstract method qualifies, including your own and old ones such as Runnable, Callable, Comparator and ActionListener. Mark yours with @FunctionalInterface; the annotation is not required, but it makes the compiler reject a second abstract method that would silently break every lambda targeting the interface.
The java.util.function catalogue
Rather than every library inventing its own single-method interfaces, the JDK provides a standard set. Learn the six shapes and the naming scheme and you can decode the rest.
| Interface | Method | Meaning |
|---|---|---|
Supplier<T> | T get() | Produce a value, no input |
Consumer<T> | void accept(T t) | Use a value, return nothing |
Function<T, R> | R apply(T t) | Transform T into R |
Predicate<T> | boolean test(T t) | Yes/no decision |
UnaryOperator<T> | T apply(T t) | Function from T to T |
BinaryOperator<T> | T apply(T a, T b) | Combine two T into one T |
Prefix Bi doubles the inputs (BiFunction<T, U, R>, BiConsumer<T, U>, BiPredicate<T, U>). Primitive specialisations exist to avoid boxing: IntPredicate, IntFunction<R> (int in), ToIntFunction<T> (int out), IntUnaryOperator, IntBinaryOperator, IntSupplier, ObjIntConsumer<T>, with Long and Double variants. When a stream calls mapToInt(ToIntFunction), that is why.
Supplier<List<String>> newList = ArrayList::new;
Consumer<String> print = System.out::println;
Function<String, Integer> parse = Integer::parseInt;
Predicate<String> isBlank = String::isBlank;
UnaryOperator<String> trim = String::strip;
BinaryOperator<Integer> max = Integer::max;
IntBinaryOperator gcd = (a, b) -> { while (b != 0) { int t = b; b = a % b; a = t; } return a; };
Reach for these before defining your own interface. A custom functional interface is justified when the name carries domain meaning (PricingRule, RetryPolicy) or when the method must declare a checked exception, which none of the standard interfaces do.
Method references
A method reference names an existing method where a lambda would merely call it. There are four forms:
| Form | Syntax | Equivalent lambda |
|---|---|---|
| Static method | Integer::parseInt | s -> Integer.parseInt(s) |
| Instance method of a particular object | System.out::println | x -> System.out.println(x) |
| Instance method of an arbitrary object of a type | String::toUpperCase | s -> s.toUpperCase() |
| Constructor | ArrayList::new | () -> new ArrayList<>() |
The third form is the one that reads oddly at first: String::compareToIgnoreCase as a Comparator<String> means "call compareToIgnoreCase on the first argument, passing the second". The first parameter becomes the receiver.
Bound references (form two) evaluate the receiver expression once, when the reference is created. this::handle or logger::info capture the current object; if the object changes later, the reference still points at the old one.
Method references are not always clearer. Person::getName is better than p -> p.getName(); but (a, b) -> a.compareTo(b) versus String::compareTo is a matter of taste, and a reference to an overloaded method can leave the compiler unable to pick an overload. When in doubt, write the lambda.
Capturing variables and the effectively-final rule
A lambda body can read local variables, parameters, fields and this from its enclosing scope. Locals and parameters, however, must be effectively final: assigned exactly once, whether or not you write the final keyword. The compiler rejects a lambda that writes to a local, and it rejects a lambda reading a local that is written anywhere after initialisation.
int base = 10;
Function<Integer, Integer> addBase = x -> x + base; // fine: base is effectively final
int counter = 0;
list.forEach(item -> counter++); // compile error: counter is modified
The rule exists because the lambda receives a copy of the value. The local variable lives in the enclosing method's stack frame; the lambda may run after that frame is gone, or on another thread. Sharing a mutable slot would require the JVM to move the variable to the heap and synchronise access, and the language designers chose to forbid it rather than hide the cost.
When you genuinely need to accumulate, the options are, in order of preference: express the computation as a reduction or collector so no shared state exists; use an AtomicInteger or LongAdder when the lambda is a callback that must count; or, as a last resort, a single-element array (int[] counter = {0}), which compiles because the reference is final even though the contents change — and which is a data race if the lambda runs concurrently.
Fields are not subject to the rule. this.counter++ inside a lambda compiles, because this is captured and the field is accessed through it. That is convenient in a single-threaded UI handler and a bug in a parallel stream.
this in lambdas versus anonymous classes
Inside a lambda, this means the enclosing instance, exactly as it does in the surrounding method. Inside an anonymous class, this is the anonymous object. This difference is the most visible reason a lambda is not sugar for an anonymous class: converting one to the other can change what this.name refers to.
Composition
The functional interfaces ship with default methods for combining instances, so small pieces can be assembled without writing new lambdas.
Predicate<String> notBlank = Predicate.not(String::isBlank);
Predicate<String> shortEnough = s -> s.length() <= 80;
Predicate<String> validTitle = notBlank.and(shortEnough);
Function<String, String> normalise = String::strip;
Function<String, String> pipeline = normalise.andThen(String::toLowerCase); // strip, then lower-case
Function<String, Integer> lengthAfter = pipeline.andThen(String::length);
Comparator<Employee> ordering = Comparator.comparing(Employee::department)
.thenComparing(Employee::salary, Comparator.reverseOrder())
.thenComparing(Employee::name, String.CASE_INSENSITIVE_ORDER);
UnaryOperator<String> identity = UnaryOperator.identity();
andThen applies the receiver first and the argument second; compose does the reverse. Predicate offers and, or, negate and the static not. Comparator is the richest: comparing, comparingInt, thenComparing, reversed, nullsFirst, nullsLast and naturalOrder. Composing comparators this way replaces hand-written compare methods that were a reliable source of sign errors.
Designing APIs around lambdas
The pay-off of lambdas is not only shorter call sites; it is that libraries can be built around behaviour parameterisation: a method that takes a strategy as an argument instead of a flag. Compare a method with three boolean parameters to one that takes a Predicate<Order> — the second is smaller, more general and testable without the caller.
public final class Retry {
public static <T> T withRetry(int attempts, Predicate<Exception> retryable, Supplier<T> action) {
Exception last = null;
for (int i = 0; i < attempts; i++) {
try {
return action.get();
} catch (Exception e) {
if (!retryable.test(e)) throw e instanceof RuntimeException r ? r : new RuntimeException(e);
last = e;
}
}
throw new IllegalStateException("Gave up after " + attempts + " attempts", last);
}
}
String body = Retry.withRetry(3, e -> e instanceof IOException, () -> client.fetch("/health"));
Guidelines for such APIs:
- Accept the most general standard interface that fits:
Supplier<T>rather than a customLoader<T>;Function<? super T, ? extends R>with wildcards as the generics guide explains, so callers can pass more than the exact types. - Prefer a primitive specialisation when the value is a primitive;
IntPredicateavoids boxing in a hot loop. - Let the lambda be pure where possible, and document when the API calls it more than once, lazily, or on another thread.
- Consider a small custom interface when it improves the call site's readability or needs a checked exception.
The one genuine limitation is checked exceptions. A Supplier<T> cannot throw IOException, so a lambda calling Files.readString must catch and wrap it. Either declare your own ThrowingSupplier<T, E extends Exception> for APIs where that is expected, or wrap in UncheckedIOException at the call site.
How lambdas are compiled
Understanding the implementation explains the behaviour. The compiler turns a lambda body into a private synthetic method in the enclosing class and emits an invokedynamic instruction at the point where the lambda appears. On first execution, the JVM's LambdaMetafactory spins up a small hidden class implementing the functional interface and links the call site to it. Consequences:
- No extra class files in your JAR, unlike anonymous classes, which each produce
Outer$1.class. - Non-capturing lambdas (no reference to locals or
this) are created once and cached; every evaluation returns the same instance. Capturing lambdas allocate a new instance per evaluation, holding copies of the captured values. - Identity is unspecified. Never compare lambdas with
==or use them as map keys; two evaluations of the same source may or may not be the same object. - Serialisation works only if the target interface is
Serializable, and it is fragile across recompilation. Avoid it.
Performance-wise, a lambda call after JIT warm-up is comparable to an interface call and usually inlines. The overheads that show up in profiles come from boxing (use primitive interfaces), from capturing allocations in hot loops, and from megamorphic call sites where one line of code dispatches to many different lambdas.
Common mistakes
Mutating captured state. The array-cell trick and field mutation compile but race under parallel execution. Reduce or collect instead.
Long lambda bodies. A ten-line block in a stream pipeline hides the pipeline's shape. Extract a named method and reference it.
Overloads that take different functional interfaces. submit(Runnable) and submit(Callable<T>) on ExecutorService already cause ambiguity with () -> doWork(). Avoid designing such overloads; if you must, give them different names.
Ignoring the checked-exception mismatch. Wrapping every call in try/catch inside the lambda is a signal to introduce a throwing interface or to restructure.
Assuming eager execution. Passing a lambda to a method does not run it. If the callee stores it and calls it later, captured objects are alive until then, which can pin large objects in memory.
Using Optional.get in a lambda chain. Compose with map/flatMap/orElse; see the Optional guide.
Comparator lambdas with subtraction. (a, b) -> a.value - b.value overflows for large values. Use Integer.compare or Comparator.comparingInt.
Key takeaways
- A lambda is an instance of a functional interface; its type comes from the context it appears in, never from the lambda itself.
java.util.functionsupplies the standard shapes —Supplier,Consumer,Function,Predicate,UnaryOperator,BinaryOperator— plusBiand primitive variants. Use them before writing your own.- Method references come in four forms; use them when the lambda would only forward its arguments.
- Captured locals must be effectively final because the lambda receives a copy; fields and
thisare captured by reference. - Compose behaviour with
andThen,compose,and,or,negateand theComparatorbuilders instead of writing new lambdas. - Lambdas compile to
invokedynamicplus a synthetic method, not to anonymous classes: no class files, cached non-capturing instances,thismeans the enclosing object, and identity is not guaranteed.
Sources and further reading
Frequently asked questions
- What is a functional interface?
- An interface with exactly one abstract method. Default and static methods do not count, and neither do methods that Object already provides, such as equals. Any functional interface can be the target type of a lambda or method reference. The @FunctionalInterface annotation is optional but makes the compiler enforce the single-method rule.
- Why must variables used in a lambda be effectively final?
- A lambda captures the value of a local variable, not the variable itself; the local lives on the stack and may be gone when the lambda runs later, possibly on another thread. Allowing writes would make the copy and the original diverge silently. If you need mutable state, use a field, an array cell, an AtomicInteger, or better, restructure with a reduction or collector.
- Is a lambda just syntax for an anonymous inner class?
- No. A lambda is compiled to a private method plus an invokedynamic call site that creates the functional-interface instance lazily; no class file is generated at compile time, this refers to the enclosing instance, and a non-capturing lambda is typically allocated once and reused. An anonymous class is a separate class with its own this and a fresh object per evaluation.
- When should I use a method reference instead of a lambda?
- When the lambda would do nothing but forward its parameters to one existing method — String::length instead of s -> s.length(). If any adaptation of the arguments is needed, or if the reference would be ambiguous or obscure, write the lambda.