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. The compiler works out everything else from the place where the lambda is used.

Lambdas arrived in Java 8 together with method references and the java.util.function package. They made it practical to pass behavior as an argument, which the stream API, Comparator factories, Map.computeIfAbsent and CompletableFuture all depend on. Before Java 8 the same thing needed an anonymous class, which took five or six lines for one line of logic.

Ways to pass behavior in Java
FormExampleSinceBest for
Named classclass ByLength implements Comparator<String>1.0Logic that is reused, tested on its own or has state
Anonymous classnew Comparator<>() { ... }1.1Interfaces with several methods, or code needing its own this
Lambda expression(a, b) -> a.length() - b.length()8Short logic written at the place it is used
Method referenceString::length8A lambda that only calls one existing method
Lambda with var parameters(var s, var n) -> s.repeat(n)11Adding 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 functional interfaces.

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.

Java
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:

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 reversed(), a default method on Comparator, which works because a lambda is a real object of that interface.
  • A single parameter needs no parentheses, as in s -> s.length(). Zero parameters or two or more need them, as in () -> "no parameters" and (a, b) -> a + b.
  • Parameter types are usually inferred. You can write them, as in (int a, int b), but then every parameter needs one; mixing typed and untyped parameters does not compile.
  • The (var s, var n) form from Java 11 still infers the types. Its purpose is to allow annotations such as (@NonNull var s), which need a type position to attach to.
  • An expression body returns its value automatically. A block body in braces, like the one that printed "-5 is negative", needs an explicit return when the interface method returns a value.

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.

Java
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:

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 () -> "hello" became a Supplier in one line and a Callable in the next. The two objects have unrelated types, so one cannot be assigned to the other even though their lambdas look the same.
  • The text x -> x * 2 printed 42 both times. As an IntUnaryOperator it works on a plain int; as a Function<Integer, Integer> it unboxes and boxes on every call.
  • Assigning a lambda to Object or to var does not compile, because neither gives the compiler a functional interface to target. A cast such as (Supplier<String>) supplies one.
  • With overloads for Runnable and Supplier, the body decides. A value like "text" fits only Supplier, and System.out.print("") returns void, so it fits only Runnable.
  • The call " both ".strip() fits both, since a method call's result may be used or discarded. The compiler chose Supplier, because JLS 15.12.2.5 prefers the interface whose method returns a value. The same rule makes ExecutorService.submit pick Callable over 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.

Java
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:

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 limit = 20 could never be seen, and the compiler rejects it.
  • Fields have no such rule. The lambda used this.counter, so it printed 0 and then 5 after the field changed. Capturing this also keeps the whole enclosing object alive as long as the lambda is.
  • Inside a lambda, this means the enclosing object, which printed "this is the Capture object". An anonymous class would have its own this instead, as covered in inner classes.
  • The for-each loop gave a b c because its variable is a new variable in each iteration. A classic for loop variable changes with i++, so () -> i does not compile; copying it to copy gave 0, 10 and 20.
  • To change state from inside a lambda, mutate an object instead of the variable. The AtomicInteger counted 3 calls and the one-element array summed to 12. The atomic version is also safe if the lambda runs on several threads.
  • The makeGreeting 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.

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.

Java
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:

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, debugEager(expensiveReport()) still built 1000 reports, because Java evaluates arguments before the call. Passing a Supplier built 0, since get() was never called. This is why java.util.logging.Logger and SLF4J 2 accept suppliers.
  • The call Optional.orElse(expensiveReport()) ran the method once even though a value was present. The orElseGet version takes a supplier and ran it 0 times, as explained on the Optional page.
  • Six computeIfAbsent 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.
  • Creating the boom lambda printed nothing unusual. The exception appeared only at run(), so its stack trace points at the caller of run(), not at the line where the lambda was written.

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.

Java
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:

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 removeIf method took a Predicate and removed Zoe; replaceAll took a UnaryOperator and upper-cased the remaining four names in place.
  • The Map.merge call took Integer::sum 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.
  • The Map.forEach method passes key and value as two lambda parameters, which is shorter than iterating over entrySet().
  • The thread ran a Runnable lambda and printed its name, worker-1. Any API that takes a Runnable or Callable, such as the ones on thread 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.

Java
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:

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 factorial(10) printed 3628800.
  • A lambda cannot declare type parameters, so no lambda can implement an interface whose single method is generic, such as Doubler.apply. A method reference to the generic method twice is allowed and worked for both a string and a double.
  • The same reference, Limits::twice, served as a Function of strings and of integers. Its type parameter is inferred separately for each target.
  • Lambda parameters share the enclosing scope, so naming one s when a local s exists fails with "variable s is already defined". Rename the parameter.
  • The standard interfaces declare no checked exceptions, so a lambda passed to map cannot throw an IOException. The usual fix is a wrapping adapter, shown in the checked exceptions section of the functional interfaces page.

Choosing a form

When to use a lambda, a method reference or a class
SituationPreferReason
One or two lines of logic at the call siteLambda expressionThe behavior is visible where it is used
The body only calls an existing methodMethod reference such as String::lengthShorter, and the method name documents the intent
Logic longer than a few linesA private method plus a method referenceThe method can be named, tested and debugged on its own
Interface with more than one abstract methodAnonymous or named classA lambda can implement only one method
The object needs its own fields or thisAnonymous or named classA lambda has no state of its own beyond captures
An expensive argument that may not be neededA Supplier lambdaThe body runs only if get() is called
Counting or collecting from inside a lambdaAtomicInteger, or a stream collectorCaptured 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.