ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume I
  5. Relationship with Lambdas
Book 1 · Volume I — Java Language Fundamentals & Object-Oriented Programming · Topic 8.4

Relationship with Lambdas

Functional interfaces, and anonymous classes versus lambdas

10 min readStage 1 · Foundations14 interview questions
Prerequisites
8.3 Anonymous Classes · 7.1 Interfaces
Covers
Functional interfaces · Anonymous class vs lambda
Related
B1V3 Ch1 Lambdas & Functional Interfaces · 1.2 Source-to-Execution Lifecycle (invokedynamic)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

A lambda expression is a concise way to provide an implementation of a functional interface — an interface with exactly one abstract method. For that case, a lambda replaces the anonymous class that Java code used before Java 8. The replacement is not just shorter syntax: lambdas have different rules for this, different object-creation behaviour, and a different compilation strategy.

JAVAThree ways to supply behaviour
// Anonymous class
Runnable r1 = new Runnable() {
    @Override public void run() { System.out.println("hello"); }
};

// Lambda — same behaviour
Runnable r2 = () -> System.out.println("hello");

// Method reference — even shorter when a method already exists
orders.sort(Comparator.comparing(Order::total));

2Why It Exists

Anonymous classes made passing behaviour verbose: five lines of ceremony around one line of logic. That verbosity discouraged functional styles such as the Streams API. Lambdas, together with a redesign of how such objects are created at run time, made behaviour-passing cheap to write and cheap to execute.

3Core Concepts

Functional interfaces

A functional interface has exactly one abstract method; default, static and private methods, and methods inherited from Object such as equals, do not count. Examples: Runnable, Callable<V>, Comparator<T>, and the java.util.function family — Function<T,R>, Supplier<T>, Consumer<T>, Predicate<T> and primitive specialisations such as IntPredicate. The optional @FunctionalInterface annotation makes the compiler enforce the rule. A lambda has no type of its own; it takes the type of the functional interface expected in its context (its target type).

Anonymous class vs lambda

Key differences between the two forms
Figure 1 — Key differences between the two forms
AspectAnonymous classLambda
Can implementAny interface or abstract/concrete classFunctional interfaces only
MethodsAny numberExactly one (the abstract method)
StateMay declare fieldsNo fields; captured values only
Meaning of thisThe anonymous object itselfThe enclosing instance (lexical scope)
ShadowingCan declare variables that shadow enclosing onesCannot redeclare enclosing local variable names
InstancesNew object each evaluationNon-capturing lambdas typically reuse a single instance
CompilationSeparate Outer$1.class filePrivate method + invokedynamic; class generated at run time
Captures enclosing instanceIn instance contexts: always before javac 18; since then only when used, or when the class is serialisableOnly if the body uses this or instance members
this refers to different objects in the two forms
Figure 2 — this refers to different objects in the two forms

4How It Works Internally

The compiler turns a lambda body into a private method of the enclosing class and emits an invokedynamic instruction at the point where the lambda is used. On first execution, the bootstrap method LambdaMetafactory generates a hidden class implementing the functional interface, whose method calls the private method. Subsequent executions reuse the linked call site. A lambda that captures nothing yields the same instance every time; a capturing lambda creates a small object holding the captured values.

From source to object: the lambda translation strategy
Figure 3 — From source to object: the lambda translation strategy

This strategy keeps class files small (no Outer$1.class per lambda), lets the JVM choose the implementation, and often lets the JIT inline the lambda body entirely. It is also why a lambda's getClass() returns an unstable, hidden class name that code must never depend on.

What an anonymous class and a lambda create and capture
Figure 4 — What an anonymous class and a lambda create and capture

Figure 4 compares the objects. A capturing lambda stores its captured values in fields of the hidden class, arg$1 and so on, and the enclosing object only if the body uses this or an instance member (Example 4). A non-capturing lambda is linked to one constant instance, so evaluating it again returns the same object; that is HotSpot behaviour, which code must not rely on.

5APIs / Features / Syntax

A lambda has three parts: parameters, an arrow and a body. The table lists the forms; method references are the shorter form when an existing method already does the job.

FormExample and meaning
() -> expression() -> "ok": no parameters, the value of the expression is returned
x -> expressiono -> o.total(): one parameter, type inferred, no parentheses needed
(a, b) -> { statements }A block body; return is needed for a value
(var a, var b) -> ...var parameters (Java 11), so that annotations can be added
(_, v) -> ...Unnamed parameter for a value the body ignores (Java 22, JEP 456)
Type::staticMethodInteger::parseInt: the arguments become the method's arguments
object::methodprefix::concat: bound receiver, evaluated once
Type::instanceMethodString::toUpperCase: the first argument becomes the receiver
Type::newArrayList::new: a constructor reference
JAVAMethodRefs.java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
 
public class MethodRefs {
    public static void main(String[] args) {
        Function<String, Integer> parse = Integer::parseInt;  // static method
        String prefix = "INV-";
        Function<String, String> tag = prefix::concat;       // bound receiver
        Function<String, String> upper = String::toUpperCase;  // unbound
        Supplier<List<String>> fresh = ArrayList::new;          // constructor
 
        List<String> ids = fresh.get();
        ids.add(tag.apply(upper.apply("a7")));
        System.out.println(ids + " " + (parse.apply("41") + 1));
    }
}
OUTPUT
[INV-A7] 42

The unnamed parameter _ is Java 22 syntax (final in Java 22, a preview in Java 21), so this listing needs Java 22 or later:

JAVAUnnamedParams.java
import java.util.Map;
import java.util.TreeMap;
 
public class UnnamedParams {
    public static void main(String[] args) {
        Map<String, Integer> stock =
                new TreeMap<>(Map.of("pen", 40, "ink", 3));
        stock.replaceAll((_, qty) -> qty + 10);       // the key is not needed
        System.out.println(stock);
    }
}
OUTPUT
{ink=13, pen=50}

6Practical Examples

Example 1 — Migrating an anonymous class to a lambda

JAVAMigration can change behaviour when this is used
// Before
button.addListener(new ClickListener() {
    private int clicks;
    @Override public void onClick(ClickEvent e) {
        log.info("clicked by {}", e.user());
        this.clicks++;  // 'this' is the listener: counts on the listener object
    }
});

// After — note the change in 'this'
button.addListener(e -> {
    log.info("clicked by {}", e.user());
    this.clicks++;  // 'this' is now the enclosing object: a different field
});

Why it matters. The fixed "Before" listing counts clicks in a field of the listener; after the migration, this.clicks compiles only because the enclosing class happens to have a clicks field too, and it now counts there. The compiler cannot warn, because both versions are valid; review every migrated this, and every local that the anonymous class shadowed.

Example 2 — Mini program: one task, three forms

Problem. Section 3 lists the differences between an anonymous class and a lambda. This program measures them: what this means, how many objects three evaluations of the same expression create, and what kind of class the JVM made.

JAVAThreeForms.java
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
import java.util.function.Supplier;
 
public class ThreeForms {
    private final String owner = "ThreeForms";
 
    Supplier<String> anonymous() {
        return new Supplier<>() {
            public String get() {
                return "anonymous: this is " + getClass().getName();
            }
        };
    }
    Supplier<String> capturing() {
        return () -> "lambda:    this is " + this.owner;
    }
    static Supplier<String> plain() { return () -> "no capture"; }
    static String fixed() { return "method ref"; }
 
    // how many distinct objects do 3 evaluations of one expression give?
    static int objects(Supplier<Supplier<String>> expression) {
        Set<Object> seen = Collections.newSetFromMap(new IdentityHashMap<>());
        for (int i = 0; i < 3; i++) seen.add(expression.get());
        return seen.size();
    }
 
    public static void main(String[] args) {
        ThreeForms f = new ThreeForms();
        System.out.println(f.anonymous().get());
        System.out.println(f.capturing().get());
        System.out.println("objects from 3 evaluations: anonymous "
                + objects(f::anonymous) + ", capturing lambda "
                + objects(f::capturing));
        System.out.println("  non-capturing lambda "
                + objects(ThreeForms::plain)
                + ", method ref " + objects(() -> ThreeForms::fixed));
        Class<?> anon = f.anonymous().getClass();
        Class<?> lambda = f.capturing().getClass();
        System.out.println("anonymous class: " + anon.isAnonymousClass()
                + " / " + lambda.isAnonymousClass()
                + ", hidden class: " + anon.isHidden()
                + " / " + lambda.isHidden());
    }
}
OUTPUT
anonymous: this is ThreeForms$1
lambda:    this is ThreeForms
objects from 3 evaluations: anonymous 3, capturing lambda 3
  non-capturing lambda 1, method ref 1
anonymous class: true / false, hidden class: false / true

Why it behaves this way. In the anonymous class, getClass() is the anonymous class ThreeForms$1; in the lambda, this.owner is the enclosing object's field. The anonymous expression and the capturing lambda create a new object each time, the capturing lambda because each object holds its own captured this. The non-capturing lambda and the method reference are linked to one instance and return it every time. A lambda's class is a hidden class, not an anonymous one, and has no class file (section 4).

Example 3 — Cases that must stay anonymous (or become named classes)

JAVAWhen a lambda cannot replace the anonymous class
// Abstract class target — not a functional interface
TimerTask task = new TimerTask() {
    @Override public void run() { refreshCache(); }
};

// More than one method
WindowListener l = new WindowAdapter() {
    @Override public void windowOpened(WindowEvent e)  { … }
    @Override public void windowClosing(WindowEvent e) { … }
};

// Needs its own state across calls
Iterator<Integer> counter = new Iterator<>() {
    private int n;
    public boolean hasNext() { return n < 10; }
    public Integer next() { return n++; }
};

Why they stay. TimerTask is an abstract class, WindowAdapter gives empty bodies for many methods so that two can be overridden, and the counter keeps n between calls; none of these is a single abstract method of an interface.

Example 4 — A lambda that captures this by accident

Problem. Section 7 warns that a lambda using an instance field captures this. This program shows what two scheduled lambdas really hold.

JAVAAccidentalCapture.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public class AccidentalCapture {
 
    static final List<Runnable> SCHEDULER = new ArrayList<>();   // long-lived
 
    static final class ReportPage {
        private final byte[] rendered = new byte[2_000_000];   // 2 MB
        private final String title;
        ReportPage(String title) { this.title = title; }
 
        void scheduleLeaky() {             // title means this.title
            SCHEDULER.add(() -> System.out.println("refresh " + title));
        }
        void scheduleSafe() {              // copy the field into a local
            String t = title;
            SCHEDULER.add(() -> System.out.println("refresh " + t));
        }
    }
 
    static List<String> captured(Object lambda) {
        return Arrays.stream(lambda.getClass().getDeclaredFields())
                .map(f -> f.getType().getSimpleName()).toList();
    }
 
    public static void main(String[] args) {
        ReportPage page = new ReportPage("Q3 sales");
        page.scheduleLeaky();
        page.scheduleSafe();
        System.out.println("leaky captures " + captured(SCHEDULER.get(0)));
        System.out.println("safe captures  " + captured(SCHEDULER.get(1)));
        SCHEDULER.forEach(Runnable::run);
    }
}
OUTPUT
leaky captures [ReportPage]
safe captures  [String]
refresh Q3 sales
refresh Q3 sales

Why it behaves this way. title inside scheduleLeaky means this.title, so the lambda captures the whole ReportPage, 2 MB of rendered output included, for as long as the scheduler holds it. scheduleSafe copies the field into a local first, so its lambda captures only the String. Both print the same, which is why the leak goes unnoticed until a heap dump shows pages retained by lambda objects.

Example 5 — A listener that must refer to itself

Problem. A one-shot listener should remove itself after the first event. A lambda cannot do it, because this in a lambda is the enclosing scope.

JAVASelfRemoving.java
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
 
public class SelfRemoving {
 
    interface Listener { void on(String event); }
 
    static final class Bus {
        private final List<Listener> listeners = new CopyOnWriteArrayList<>();
        void add(Listener l) { listeners.add(l); }
        void remove(Listener l) { listeners.remove(l); }
        void publish(String event) { listeners.forEach(l -> l.on(event)); }
        int size() { return listeners.size(); }
    }
 
    public static void main(String[] args) {
        Bus bus = new Bus();
        bus.add(new Listener() {                   // one-shot: removes itself
            public void on(String event) {
                System.out.println("once:   " + event);
                bus.remove(this);                   // this = the listener
            }
        });
        bus.add(event -> System.out.println("always: " + event));
        bus.publish("deploy started");
        bus.publish("deploy finished");
        System.out.println("listeners left: " + bus.size());
    }
}
OUTPUT
once:   deploy started
always: deploy started
always: deploy finished
listeners left: 1

Why it behaves this way. Inside the anonymous class, this is the listener, so bus.remove(this) removes exactly it; the CopyOnWriteArrayList lets it do so while the bus is iterating. A lambda would have to be stored in a variable or field first and then remove that, which is clumsier and easy to get wrong.

7Common Problems & Mistakes

MistakeConsequenceBetter approach
Mechanical migration that changes the meaning of this or of shadowed variablesThe code still compiles but updates another object's field (Example 1)Review each migrated this and each shadowed name; keep the class where this means the object
Long multi-line lambdas that hide business logicStack traces show lambda$process$3, and the logic cannot be tested aloneExtract a named method and pass a method reference
Lambdas capturing this unintentionally through an instance fieldStored in a long-lived structure, they keep the enclosing object alive (Example 4)Copy the field into a local before the lambda
Relying on lambda identity or getClass()Whether two evaluations give the same object, and the class names, are implementation detailsCompare by behaviour or by an explicit key; never by == or class name
Serialising lambdasWorks only with an intersection cast and breaks when the source changesSerialise data, not behaviour: an enum or a record that selects the behaviour
Wrapping checked exceptions badly inside lambdasA catch-all that swallows IOException in a stream hides failuresThrow an UncheckedIOException with the cause, or loop explicitly

8Performance & Production Considerations

Lambdas are generally at least as efficient as anonymous classes: no class file to load per use site, instance reuse for non-capturing lambdas, and good inlining. The first execution of each lambda call site does some bootstrap work, which contributes to startup time in large applications — one of the costs that AOT class loading and linking caches in recent JDKs address (1.2). In stack traces, lambda frames appear as lambda$method$N, which is worth recognising when reading production logs.

  • A capturing lambda allocates one small object per evaluation; in a hot loop, the JIT usually removes it by escape analysis, but a lambda created once outside the loop is never slower.
  • When a heap dump shows objects of a class named like Owner$$Lambda/0x... retaining large objects, look at their arg$ fields: they are the captured values (Example 4).

9Architecture & Design Considerations

Functional interfaces make behaviour a first-class parameter, which simplifies several design patterns: Strategy, Command, Template Method callbacks and Observer can often be expressed with a functional interface and lambdas instead of class hierarchies. Keep the functional interface domain-named at important boundaries (PriceRule, RetryPolicy) rather than exposing raw Function<A,B> everywhere — the name documents the contract.

Choosing between a lambda, a method reference and a class
Figure 5 — Choosing between a lambda, a method reference and a class

10Interview Questions & Answers

Q1L1 · BasicConcept

What is a functional interface?

An interface with exactly one abstract method, such as Runnable, Comparator or Function. Lambdas and method references can implement it. Default, static, private and Object methods do not count.

Q2L2 · IntermediateConcept

What are the main differences between an anonymous class and a lambda?

A lambda can implement only a functional interface, has no state of its own, treats this as the enclosing instance, cannot shadow enclosing locals, and is compiled with invokedynamic rather than a separate class file. An anonymous class can extend classes, implement several methods, have fields, and its this refers to itself.

Q3L2 · IntermediateConcept

What does this refer to inside a lambda?

The enclosing instance, exactly as in the surrounding code — lambdas are lexically scoped. In an anonymous class, this refers to the anonymous object. So a lambda cannot refer to itself; an object that must, such as a self-removing listener, stays an anonymous class (Example 5).

Q4L3 · Senior EngineerInternals

How are lambdas compiled and created at run time?

The body becomes a private method; the use site becomes an invokedynamic call bootstrapped by LambdaMetafactory, which generates a hidden class implementing the functional interface. Non-capturing lambdas typically reuse one instance; capturing ones create an object holding the captured values.

Q5L3 · Senior EngineerTricky

When can you not replace an anonymous class with a lambda?

When the target type is a class (abstract or concrete), when more than one method must be implemented, when the object needs its own fields, when code relies on this meaning the object itself, or when a subclass is needed to preserve generic type information.

Q6L4 · Technical ArchitectDesign

How do functional interfaces change the way you apply design patterns?

Patterns whose variation is one operation — Strategy, Command, simple Template Method hooks, callbacks — can take a functional interface and be supplied with lambdas, avoiding a class per variant. For variants with several operations or significant state, classes remain clearer. Give boundary interfaces domain names so contracts stay explicit.

Q7L1 · BasicConcept

What are the four kinds of method reference?

A static method (Integer::parseInt), an instance method of a particular object, the bound receiver (prefix::concat), an instance method of an arbitrary object, where the first argument becomes the receiver (String::toUpperCase), and a constructor (ArrayList::new).

Q8L2 · IntermediateCode

What does this program print?

JAVALambdaThisQuiz.java
public class LambdaThisQuiz {
    String who = "outer";
 
    void run() {
        Runnable anon = new Runnable() {
            String who = "anon";
            public void run() { System.out.print(this.who + " "); }
        };
        Runnable lambda = () -> System.out.print(this.who + " ");
        anon.run();
        lambda.run();
        System.out.println(anon.getClass().isAnonymousClass() + " "
                + lambda.getClass().isAnonymousClass());
    }
 
    public static void main(String[] args) {
        new LambdaThisQuiz().run();
    }
}

It prints anon outer true false. In the anonymous class, this.who is the anonymous object's own field. In the lambda, this is the enclosing LambdaThisQuiz object, so it reads outer. A lambda's class is a hidden class generated at run time, not an anonymous class, so isAnonymousClass() is false.

Q9L3 · Senior EngineerTricky

Does evaluating the same lambda expression twice give the same object?

It may. A non-capturing lambda is typically linked to one constant instance, so sup() == sup() is true on HotSpot; a capturing lambda creates a new object each time (Example 2). The language does not specify either, so code must never depend on lambda identity, for example as a key for removing a listener.

Q10L3 · Senior EngineerInternals

Where do the captured values of a lambda live?

In private final fields (arg$1 ...) of the hidden class that LambdaMetafactory generated; the invokedynamic call site passes them in when it creates the object. The enclosing object is captured like any other value, and only when the body uses this or an instance member (Example 4).

Q11L3 · Senior EngineerScenario

After a refactoring that replaced anonymous listeners with lambdas, a UI counter stopped increasing and another counter doubled. What happened?

The anonymous listeners incremented their own clicks field through this. In the lambdas this is the enclosing object, which also had a clicks field, so the increments went there (Example 1). Restore the counting where it belongs: keep the anonymous class or a named class where the listener owns state, or move the counter deliberately and rename fields so that shadowing cannot hide such a change.

Q12L3 · Senior EngineerTrade-off

Method reference or lambda: which do you prefer, and when is a lambda clearer?

A method reference when a named method already does exactly the job; it names the intent and keeps stack traces readable. A lambda when arguments must be adapted, reordered or combined, for example o -> o.total().compareTo(limit) > 0. Avoid references that need a mental lookup of which overload or receiver is meant.

Q13L4 · Technical ArchitectDesign

How would you design a callback API so that callers can use lambdas but still unregister them reliably?

Do not make callers keep the lambda to remove it later, since identity is not guaranteed to be meaningful. Return a handle from register, such as an AutoCloseable subscription, and let close() remove exactly that registration; then lambdas, method references and classes all work the same way, and try-with-resources can scope a subscription.

Q14L5 · Solution ArchitectTrade-off

Should a public API expose java.util.function types such as Function<Order, Money>, or its own functional interfaces?

Use your own named interfaces at important boundaries (PricingRule, RetryPolicy): the name documents the contract, it can declare checked exceptions, add default methods and evolve, and its Javadoc explains the rules. Generic java.util.function types are fine for internal plumbing and for small utility parameters. Both accept the same lambdas, so callers pay nothing for the clearer contract.

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • Functional interfaces have exactly one abstract method and are the targets of lambdas.
  • Lambdas replace anonymous classes only for functional interfaces.
  • this in a lambda is the enclosing instance; in an anonymous class it is the anonymous object.
  • Lambdas use invokedynamic and hidden classes; non-capturing lambdas reuse one instance.
  • Keep anonymous or named classes for class targets, multiple methods or state.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.