What is a Lambda

Behaviour as a Value

A lambda expression is a short, unnamed function that you can store in a variable, pass to a method or return from a method. Lambdas came in Java 8 and are the base of the Streams API, CompletableFuture, event handlers and almost every modern Java library.

Before Java 8 you had to write an anonymous inner class to pass behaviour. A lambda says the same thing in one line.

Anonymous Class vs Lambda

Example

Both versions sort the same list by length. The lambda removes all the boilerplate.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> cities = new ArrayList<>(List.of("Mumbai", "Pune", "Bengaluru", "Delhi"));

        // Before Java 8: anonymous inner class
        Collections.sort(cities, new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                return Integer.compare(a.length(), b.length());
            }
        });
        System.out.println("Anonymous class: " + cities);

        // Java 8+: lambda
        cities.sort((a, b) -> Integer.compare(b.length(), a.length()));
        System.out.println("Lambda (longest first): " + cities);
    }
}

Output

Anonymous class: [Pune, Delhi, Mumbai, Bengaluru]
Lambda (longest first): [Bengaluru, Mumbai, Delhi, Pune]

Where Lambdas Can Be Used

A lambda can be used only where Java expects a functional interface: an interface with exactly one abstract method. The lambda becomes the body of that method. Comparator, Runnable, Callable and everything in java.util.function are functional interfaces.

Tip: Think of a lambda as "an implementation of the single method of an interface, written inline".