Skip to content
Tutorials Center
My learning

Topics

Lesson 98 of 201 ยท Generics and Functional Programming

Lambda Expressions

Learn Java lambda expressions - syntax forms, target typing, capturing effectively final variables, this in lambdas, and using lambdas with forEach, removeIf, sort and replaceAll.

A lambda expression is a short way to write a piece of behavior that you pass to a method, store in a variable or return as a result. Instead of creating a whole class just to say "compare these two strings by length" or "keep only the even numbers", you write the logic itself: (a, b) -> a.length() - b.length() or n -> n % 2 == 0.

Lambdas arrived in Java 8 (2014) and changed how Java code looks. Sorting, filtering, event handling, threads, streams and most modern APIs take lambdas. This lesson covers the syntax in all its forms, how the compiler figures out what a lambda means (target typing), which variables a lambda can use, how this behaves, and the collection methods that make lambdas useful from day one.

From anonymous class to lambda

Before Java 8, passing behavior meant writing an anonymous class. Here's a list sorted by word length, the old way and the new way:

Java The same Comparator, three ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The anonymous class needs six lines to say one thing; the lambda says it in one. Everything the compiler can work out on its own (the interface name, the method name, the parameter types, return) disappears.

Lambda syntax

A lambda has a parameter list, an arrow -> and a body. The body is either a single expression, whose value is returned automatically, or a block in braces with statements and an explicit return:

Java
() -> 42                                  // no parameters
x -> x * 2                                // one parameter: parentheses optional
(x, y) -> x + y                           // two or more: parentheses required
(String s) -> s.isBlank()                 // explicit parameter type
(var a, var b) -> a.equals(b)             // var parameters (Java 11), useful with annotations
(a, b) -> {                               // block body: braces, statements, return
    int diff = a.length() - b.length();
    return diff != 0 ? diff : a.compareTo(b);
}

A few rules keep the syntax unambiguous:

  • With one parameter and no type, parentheses are optional: x -> .... With zero, two or more parameters, or with a type, they're required.
  • Either give all parameters types or none: (String a, b) -> ... doesn't compile.
  • An expression body returns its value; a block body needs return if the interface method returns something. A block body for a void method may not return a value.
  • Since Java 22, you can name a parameter you don't use _: (_, value) -> value * 2.

Target typing: what is a lambda?

A lambda by itself has no type. It gets one from its target, the place where it's used: a variable declaration, a method parameter, a return statement or a cast. The target must be a functional interface, an interface with exactly one abstract method, such as Comparator, Runnable or Predicate. The lambda becomes an implementation of that one method.

The same lambda text can therefore mean different things in different places:

Java One lambda, different target types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

(a, b) -> a + b adds boxed integers, adds primitive ints, or concatenates strings, depending on the target. The parameter types are inferred from the target interface's method: in Discount, price is a double because apply takes a double.

Because the type comes from the target, a lambda can't stand alone:

Java
var f = x -> x * 2;              // compile error: lambda expression needs an explicit target-type
Object o = () -> "hi";           // compile error: Object is not a functional interface
Runnable r = () -> IO.println("hi");   // fine

Functional Interfaces tours the interfaces in java.util.function that cover nearly every shape a lambda can have.

Capturing variables: effectively final

A lambda can use variables from the method around it. This is called capturing. The rule: captured local variables must be final or effectively final, meaning they're never reassigned after initialization. (You met effectively final in Constants and final.)

Java
String greeting = "Hello";               // never reassigned: effectively final
Runnable hi = () -> IO.println(greeting + "!");    // OK

int count = 0;
Runnable bump = () -> count++;           // compile error: local variables referenced from
                                         // a lambda expression must be final or effectively final

Why the rule? A lambda may run later, on another thread, after the method has returned and its local variables are gone. Java therefore captures the value of the variable, not the variable itself. If reassignment were allowed, the lambda and the method would silently see different values. Forbidding it keeps the behavior obvious.

The restriction applies to local variables and parameters only. Fields and array elements can be modified, because the lambda reaches them through an object reference:

Java What a lambda may capture and change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Mutating captured objects (like log above) is legal, but use it with care: if the lambda runs on several threads, a plain ArrayList isn't safe. Workarounds such as a one-element array (int[] counter = {0};) exist and you'll see them online, but they usually signal that a stream operation such as count() or sum() would be clearer (Streams).

this inside a lambda

A lambda is not a new scope the way an anonymous class is. Inside a lambda:

  • this means the enclosing object, exactly as in the surrounding method. In an anonymous class, this is the anonymous object itself.
  • You can't redeclare a local variable name from the enclosing method, while an anonymous class can shadow it.
Java this in a lambda versus an anonymous class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The lambda prints the Main object; the anonymous class prints its own generated class name Main$1 and needs Main.this to reach the outer object. This makes lambdas natural inside instance methods: calling this.save(...) or a field from a lambda just works.

Under the hood, lambdas aren't compiled to anonymous classes either. The compiler turns the body into a private method and uses the invokedynamic instruction to create the functional-interface object at runtime, which is cheaper than loading a class per lambda.

Lambdas with collections

The collection interfaces gained default methods in Java 8 that take lambdas. They replace many hand-written loops:

Method What it does
Iterable.forEach(action) runs the action for each element
Collection.removeIf(filter) removes every element matching the predicate; returns whether anything was removed
List.replaceAll(operator) replaces each element with the result of a function
List.sort(comparator) sorts in place
Map.forEach((k, v) -> ...) visits each entry
Map.replaceAll((k, v) -> newV) replaces every value
Map.computeIfAbsent(k, k -> v) creates a value only when the key is missing
Map.merge(k, v, (old, v) -> ...) combines a new value with an existing one
Java forEach, removeIf, replaceAll, sort and map methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

removeIf is the safe way to remove while iterating: no ConcurrentModificationException, no index bookkeeping. computeIfAbsent creates the list for a new domain only the first time it's needed. merge handles "insert 1 or add 1 to the existing count" in one call. The HashMap lesson goes deeper into merge and compute.

Use forEach for simple actions. If the loop body needs break, continue, a checked exception or a local counter, a regular for-each loop is clearer than forcing it into a lambda.

Lambdas and checked exceptions

The functional interfaces in java.util.function don't declare throws. So a lambda body passed to one of them can't throw a checked exception like IOException without catching it:

Java
List<Path> paths = ...;
paths.forEach(p -> Files.delete(p));        // compile error: unreported exception IOException

paths.forEach(p -> {
    try {
        Files.delete(p);
    } catch (IOException e) {
        throw new UncheckedIOException(e);  // wrap it in an unchecked exception
    }
});

Wrapping in UncheckedIOException (or your own runtime exception) is the standard solution. Another is to declare your own functional interface whose method has a throws clause, which Functional Interfaces shows.

Behavior as a value

Because a lambda is an object, you can store it, put it in collections and return it from methods. This lets you choose behavior at runtime without if chains:

Java Lambdas in a map and returned from methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

percentOff(10) returns a new function each time, each remembering its own percent. That's a closure: a function bundled with the values it captured. andThen chains two functions into a new one; composing functions like this is a major theme of Functional Interfaces and Functional Programming in Java.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these is NOT a valid lambda expression?

    Either every parameter has a declared type or none does. Mixing int a with an untyped b is a compile error.
  2. 2. What happens? int total = 0; list.forEach(n -> total += n);

    A lambda can't modify a captured local variable. Use a stream sum, a regular loop, or a field instead.
  3. 3. Inside a lambda in an instance method, what does this refer to?

    Lambdas don't introduce a new scope for this. Only anonymous classes have their own this.
  4. 4. Why doesn't var f = x -> x * 2; compile?

    The meaning of a lambda comes from its target type. Declare the variable as, for example, IntUnaryOperator or Function<Integer, Integer>.
  5. 5. What does this print? List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4)); nums.removeIf(n -> n % 2 == 0); nums.replaceAll(n -> n * 10); IO.println(nums);

    removeIf drops the even numbers, leaving [1, 3], and replaceAll multiplies each remaining element by 10.

Summary

  • A lambda is a compact implementation of a functional interface: (parameters) -> expression or (parameters) -> { statements }.
  • Parentheses are optional for one untyped parameter; types are inferred from the target, or given for all parameters (including var).
  • A lambda's type comes from its target (variable, parameter, return or cast), which must be a functional interface; var can't hold a lambda.
  • Lambdas may capture final or effectively final local variables; fields and the contents of captured objects can change.
  • this inside a lambda is the enclosing object, unlike in anonymous classes.
  • Collection methods forEach, removeIf, replaceAll, sort, and map methods forEach, computeIfAbsent, merge, replaceAll replace many loops.
  • Lambdas for java.util.function interfaces can't throw checked exceptions; wrap them in unchecked exceptions.

Next: Functional Interfaces, a tour of Function, Predicate, Consumer, Supplier and friends, and how to combine them.