Running on Java 21-ea+24-2086 (Preview)
Home of The JavaSpecialists' Newsletter

3.18 Converting Anonymous Inner Class to Lambda

Juppies 2 by Dr Heinz M. Kabutz

Java has often been accused of being too verbose. This has advantages and disadvantages. Its verbosity means that humans do not need to interpret what the code does - it is obvious for all to see.

Our anonymous inner classes are rather verbose. In the ORIGINAL_SCRAMBLER, we already know that we are making a Scrambler, because that is the type of the field declared on the left-hand side. So why do we have to repeat it? We also know that if there is only a single abstract method in the interface, it is very likely going to be this one that we are implementing. So why do we have to repeat the name of the interface in new Scrambler() and why do we need to explicitly state the name of the method scramble(char[] letters) when it is obvious that this would be the only method we could be implementing. We can deduce all that by just seeing that the type of the field is a Scrambler.

Since we have only one abstract method in our interface, we can replace the anonymous type with a lambda.

When making the lambda for the ORIGINAL_SCRAMBLER, we notice that we cannot put the curly braces and the comment on a single line. The reason is that when we write a comment with // anything on the right side of that is considered a comment, even our closing curly brace. This type of comment is called an end-of-line comment. We can also use a "traditional comment", which is like in C where we start with /* and end with */. By changing the comment we are able to wrap the comment with braces on a single line.

We also change the RANDOM_SCRAMBLER and the SORTED_SCRAMBLER to use lambdas instead of anonymous types.


When you load these comments, you'll be connected to Disqus. Privacy Statement.

Table of Contents

We hope you enjoyed this tutorial. If you did, you will also enjoy our courses. We suggest you start with Extreme Java - Advanced Java, followed by Extreme Java - Concurrency Performance for Java 8.

About the Author

Heinz Kabutz Java Conference Speaker

Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz

Superpack '23

Superpack '23 Our entire Java Specialists Training in one huge bundle more...

Free Java Book

Dynamic Proxies in Java Book
Java Training

We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.

Java Consulting

We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...

Java Emergency?

If your system is down, we will review it for 15 minutes and give you our findings for just 1 € without any obligation.