Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Modern Java

    Lambdas

    A lambda expression is an anonymous function: a piece of behaviour written inline and passed around as a value.

    Chapter 1 of 115 min read

    Start With the Problem#

    Three tasks on StudyBuddy's student list: "names of students scoring ≥ 150, highest first", "students grouped by city", "average score per city". In the Java of 2010, the first one alone looks like this:

    Java
    List<Student> passing = new ArrayList<>();
    
    for (Student s : students) {
        if (s.score() >= 150) passing.add(s);
    }
    
    Collections.sort(
        passing,
        new Comparator<Student>() {
            // an anonymous class (03_java_oop.md Ch 10)
            @Override
            public int compare(Student a, Student b) {
                int c = Integer.compare(b.score(), a.score());
                return c != 0 ? c : a.name().compareTo(b.name());
            }
        }
    );
    
    List<String> names = new ArrayList<>();
    
    for (Student s : passing) names.add(s.name());

    Fifteen lines of how (make a list, loop, add, sort, loop again) hiding one line of what. And every "maybe there's no result" method returns null, waiting to throw a NullPointerException.

    From Java 8 onwards the same task is:

    Java
    List<String> names = students
        .stream()
        .filter(s -> s.score() >= 150)
        .sorted(
            Comparator.comparingInt(Student::score).reversed().thenComparing(Student::name)
        )
        .map(Student::name)
        .toList();

    This file teaches every piece of that — and the other features added from Java 8 to 21.

    The Plain Picture#

    Instead of hiring a whole company to do one small job ("please create a Comparator Department that compares by length"), you hand someone a sticky note with the instruction on it: "compare by length". The note is the instruction, and you can pass it to whoever needs it.

    The Real Names#

    • A lambda expression is an anonymous function: a piece of behaviour written inline and passed around as a value.

    • Syntax: (parameters) -> body.

    Java
    (a, b) -> Integer.compare(a.length(), b.length())      // two parameters, expression body
    s -> s >= 150                                          // one parameter: parentheses optional
    () -> new ArrayList<>()                                // no parameters
    (String msg) -> System.out.println(msg)                // explicit parameter type (usually inferred)
    s -> {                                                 // block body: needs braces and return
        int bonus = s > 100 ? 20 : 0;
        return s + bonus;
    }

    Under the Hood#

    Capturing variables — "effectively final"#

    A lambda can use local variables from around it — captures them — but only if they're never changed:

    Java
    int bonus = 20;
    
    Function<Integer, Integer> withBonus = s -> s + bonus; // captures bonus
    
    System.out.println(withBonus.apply(180)); // 200

    If you change bonus anywhere (even after the lambda), the compiler refuses:

    Output
    error: local variables referenced from a lambda expression must be final or effectively final

    Effectively final = never reassigned after initialisation, even without the final keyword. Why the rule: a lambda may run later, or on another thread (Concurrency), after the method has returned and its stack frame is gone (Operating Systems Ch 6). Java copies the captured value into the lambda; if the variable could still change, the copy and the original would silently disagree. (Fields of objects can be changed — a lambda holds a reference to the object — but then thread-safety becomes your problem.)

    Workaround you'll see in DSA code: to count inside a lambda, use a one-element array or an AtomicInteger: int[] count = {0}; list.forEach(x -> count[0]++); — or better, restructure to use a stream's count().

    How lambdas run: they aren't compiled into anonymous classes. The compiler emits an invokedynamic instruction, and the JVM creates a small implementation the first time it runs — lighter than an anonymous class, and it doesn't capture this unless the lambda uses it.

    Check yourself

    3 questions
    1

    What is a lambda?

    Show answer

    An anonymous function — behaviour written inline and passed as a value.

    2

    Rewrite new Comparator<String>() { public int compare(String a, String b) { return a.compareTo(b); } } as a lambda.

    Show answer

    (a, b) -> a.compareTo(b).

    3

    What does "effectively final" mean, and why must captured variables be effectively final?

    Show answer

    Never reassigned after initialisation; because the lambda gets a copy of the value and may run later or on another thread, so the variable must not change.