DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Using Java Stream Gatherers To Improve Stateful Operations
  • How to Merge HTML Documents in Java
  • The Future of Java and AI: Coding in 2025

Trending

  • Scaling Microservices With Docker and Kubernetes on Production
  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  • Modern Test Automation With AI (LLM) and Playwright MCP
  • Event-Driven Microservices: How Kafka and RabbitMQ Power Scalable Systems
  1. DZone
  2. Coding
  3. Java
  4. From Java Anonymous Class to Single Line Lambda in 3 Steps

From Java Anonymous Class to Single Line Lambda in 3 Steps

See the steps involved in transforming traditional Java anonymous classes into Java 8 lambdas.

By 
Matthew Casperson user avatar
Matthew Casperson
·
Jun. 01, 16 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
65.4K Views

Join the DZone community and get the full member experience.

Join For Free

When you first encounter lambda syntax in Java 8, it can be a bit confusing. Those arrows and naked parameters are unlike any Java code that has come before it, but there is actually a very simple progression from the pre-Java 8 anonymous classes to the one line lambda syntax that is now available. Let’s take a look at how you migrate to the single-line lambda syntax.

Anonymous Classes

This is the traditional Java way one off methods were defined. Anonymous classes are unnamed instances of an interface or base class that are defined and instantiated with a single new command.

Given a standard formatting scheme, this style of code takes up at least 6 lines. This is quite verbose given the strides most programming languages have made in their expressiveness over the last few years.

    @Test
    public void anonymousClass() {
        final String greeting = HELLO_WORLD_EXECUTOR.callHelloWorld(new Greeting() {
            @Override
            public String hello(String name) {
                return "Hello " + name;
            }
        });

        Assert.assertEquals("Hello Matthew", greeting);
    }

Removing the method name

Lambdas in Java are defined via interfaces that have a single non-default method. It is the body of this method that you are populating when you construct a lambda.

Because there is a single method, the compiler knows what the method is called, so we no longer have to write this method name ourselves.

Stripping out the method name, and placing an arrow between the parameter list and the method body is the first transition between an anonymous class and a single line lambda.

    @Test
    public void firstLevel() {
        final String greeting = HELLO_WORLD_EXECUTOR.callHelloWorld((String name) -> {
            return "Hello " + name;
        });

        Assert.assertEquals("Hello Matthew", greeting);
    }

Removing the parameter types

Just as the compiler knows the name of the method you are populating, it also knows the types of the parameters. Removing these parameter types saves us some typing while still retaining the strongly typed guarantees provided by the Java language.

    @Test
    public void secondLevel() {
        final String greeting = HELLO_WORLD_EXECUTOR.callHelloWorld(name -> {
            return "Hello " + name;
        });

        Assert.assertEquals("Hello Matthew", greeting);
    }

Removing the return statement

The final piece of information that the compile can extract from the single method in our functional interface is the return type. When defining a single line lambda the compiler will use the result of the statement that is executed as the return value. This means we no longer need the return statement, and have converted the initial anonymous class into a single line lambda.

    @Test
    public void thirdLevel() {
        final String greeting = HELLO_WORLD_EXECUTOR.callHelloWorld(name -> "Hello " + name);

        Assert.assertEquals("Hello Matthew", greeting);
    }

Grab the source code for this article from GitHub.

Java (programming language)

Published at DZone with permission of Matthew Casperson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Using Java Stream Gatherers To Improve Stateful Operations
  • How to Merge HTML Documents in Java
  • The Future of Java and AI: Coding in 2025

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!