Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

From Java Anonymous Class to Single Line Lambda in 3 Steps

DZone's Guide to

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.

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's 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.

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:
java ,types ,method ,classes ,typed ,lambda ,anonymous ,syntax ,class

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}