00:00

Lambda Expressions in Java 8

Last updated: · Standard (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:

LambdaSyntax.java
(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.

LambdaBasics.java
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));
    }
}
Output
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.

EffectivelyFinal.java
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();
    }
}
Output
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.

How the compiler turns a lambda into an object The lambda (a, b) -> a.compareTo(b) is checked against the target type Comparator<String>, whose single abstract method is compare(String, String). The result is an object that implements Comparator. (a, b) -> a.compareTo(b) lambda in the source Target type Comparator<String> compare(String, String) single abstract method Comparator object passed to sort()
Figure 1: The target type decides what a lambda means. The same lambda text could also fit a different interface with a compatible 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

TaskBefore Java 8Java 8 lambda
Run a tasknew Runnable() { public void run() { ... } }() -> work()
Sort strings by lengthAnonymous Comparator class(a, b) -> a.length() - b.length()
Loop and printfor (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.
  • this inside 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 Function cannot call a method that throws IOException directly.
  • 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) -> expression or a block body with return.
  • Captured local variables must be final or effectively final.
  • Lambdas replace most anonymous classes and power the Stream API.

Related Tutorials

8. References