Course – LS (cat=Java)

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this tutorial, we'll learn how to convert an anonymous class into a lambda expression in Java.

First, we'll start with a little bit of background about what an anonymous class is. Then we'll demonstrate how to answer our central question using practical examples.

2. Anonymous Classes in Java

In short, an anonymous class, as the name indicates, is an inner class with no name. Since it has no name, we need to declare and instantiate it at the same time in one single expression.

By design, an anonymous class extends a class or implements an interface.

For example, we can use Runnable as an anonymous class to create a new thread in Java. The syntax is like the invocation of a constructor, except that we need to put the class definition inside a block:

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        ...
    }
});

Now that we know what an anonymous class is, let's see how we can rewrite it using a lambda expression.

3. Anonymous Class as a Lambda Expression

Lambda expressions offer a convenient shortcut to define an anonymous class more concisely and directly.

However, this is only possible if the anonymous class has only one single method. So, let's see how to convert an anonymous class to a lambda expression step by step.

3.1. Defining the Anonymous Class

For instance, let's consider the Sender interface:

public interface Sender {
    String send(String message);
}

As we can see, the interface has only one single declared method. This type of interface is called a functional interface.

Next, let's create the SenderService interface:

public interface SenderService {
    String callSender(Sender sender);
}

Since the callSender() method accepts a Sender object as a parameter, we can pass it as an anonymous class.

Now, we're going to create two implementations of the SenderService interface.

First, let's create the EmailSenderService class:

public class EmailSenderService implements SenderService {

    @Override
    public String callSender(Sender sender) {
        return sender.send("Email Notification");
    }
}

Next, let's create the SmsSenderService class:

public class SmsSenderService implements SenderService {

    @Override
    public String callSender(Sender sender) {
        return sender.send("SMS Notification");
    }
}

Now that we've put the pieces together, let's create a first test case where we pass the Sender object as an anonymous class:

@Test
public void whenPassingAnonymousClass_thenSuccess() {
    SenderService emailSenderService = new EmailSenderService();

    String emailNotif = emailSenderService.callSender(new Sender() {
        @Override
        public String send(String message) {
            return message;
        }
    });

    assertEquals(emailNotif, "Email Notification");
}

As shown above, we passed the Sender object as an anonymous class and overrode the send() method.

3.2. Converting the Anonymous Class

Now, let's try to rewrite the previous test case in a more concise way using a lambda expression.

Since send() is the only defined method, the compiler knows what method to call, so there's no need to override it explicitly.

To convert the anonymous class, we need to omit the new keyword and the method name:

@Test
public void whenPassingLambdaExpression_thenSuccess() {
    SenderService smsSenderService = new SmsSenderService();

    String smsNotif = smsSenderService.callSender((String message) -> {
        return message;
    });

    assertEquals(smsNotif, "SMS Notification");
}

As we can see, we replaced the anonymous class with an arrow between the send() parameter and its body.

We can enhance this even more: We can change the lambda statement to a lambda expression by removing the parameter type and the return statement:

String smsNotif = smsSenderService.callSender(message -> message);

As we can see, we don't have to specify the parameter type as the compiler can infer it implicitly.

4. Conclusion

In this article, we learned how to replace an anonymous class with a lambda expression in Java.

Along the way, we explained what an anonymous class is and how to convert it into a lambda expression.

As always, the code used in this article can be found over on GitHub.

Course – LS (cat=Java)

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!