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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Getting Started With Agentic Workflows in Java and Quarkus
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j
  • Alternative Structured Concurrency
  • Jakarta EE 12: Entering the Data Age of Enterprise Java

Trending

  • Java in a Container: Efficient Development and Deployment With Docker
  • Clean Code: Concurrency Patterns, Context Management, and Goroutine Safety, Part 5
  • AI in Software Development: A Mirror, Not a Magic Wand
  • Reactive Kafka With Spring Boot
  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.7K 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. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Getting Started With Agentic Workflows in Java and Quarkus
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j
  • Alternative Structured Concurrency
  • Jakarta EE 12: Entering the Data Age of Enterprise Java

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook