Sitelet https://github.com/javaevolved/javaevolved.github.io/issues/181
Skip to content

[Pattern] Anonymous classes to lambdas and method references #181

Description

@brunoborges

Category

language

Slug

anonymous-classes-to-lambdas

Title

Anonymous classes to lambdas and method references

Difficulty

beginner

Since JDK

8

Summary

Replace single-method anonymous classes with concise lambdas and method references.

Old code label

Anonymous class

Old code

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent event) {
        save(event);
    }
});

Modern code label

Java 8+

Modern code

button.addActionListener(this::save);

Explanation

Functional interfaces can be implemented with lambdas or method references. This removes anonymous-class ceremony while preserving static typing and the same callback contract.

Why the modern way wins

⚡ Less boilerplate — Removes the class declaration and override ceremony.
👁 Better readability — Keeps attention on the operation being performed.
🔒 Still type-safe — The compiler checks the target functional-interface signature.

Metadata

Metadata

Assignees

No one assigned

    Labels

    slugNew or updated pattern snippet (category/slug.json)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions