Monday, April 24, 2023

How to replace Anonymous Class to Lambda Expression in Java 8? Example Tutorial

Hello guys, you may be thinking why I am talking about Anonymous class now when many Java programmers have already switched to Java 8 and many have already moved on from Anonymous class to Lambda expression in? Well, I am doing it because I am seeing many Java programmers who find it difficult to write and read code using lambda expression in new Java 8 way. It's also my own experience that if you know the problem first, you can better understand the solution (lambda expression). Some of you might remember, the opening scene of MI 2 (Mission Impossible 2), when Nekhorovich says to Dimitri that "Every search for a hero must begin with something that every hero requires, a villain. Therefore, in our search for a hero, Belairiform, we created the monster, Chimera"

Well, Anonymous class is not that sort of monster but it is one of the reason which makes lambda expression hero of Java 8.  Though Anonymous class is not the only reason lambda expression was introduced in Java, it provides you a nice problem solution analogue to understand the use of lambda expression in Java and how it can help in writing cleaner, more readable code.

If you know the purpose of Anonymous class in Java, which is a way to pass a block of dynamic code to a function, you will understand the purpose of lambda expression too and this is what you will learn here. In this article, I'll show you three very common Java examples using Anonymous class which will help you to learn and understand lambda expression better.



3 Examples of Anonymous Class which can be replaced with Lambda Expression

Here are three common examples where I have used Anonymous class in past and which can be better written using Lambda expression and method reference in Java:


1. Sorting a List using Comparator

One of the most common place where you might have seen Anonymous class in Java is while sorting list of objects. Suppose you have a list of Books and you want to sort them on price. You use Collections.sort() method which requires code to compare object because it does know sorting but doesn't know how to compare objects. 

Now, how do you pass a block of code to a function in Java? You just can't. Java is an object-oriented language, so you must wrap the code inside a method and then wrap the method inside a class, and then create an object and pass that object to the function. This is painful isn't it?

Anonymous class solved that problem by doing all that on the fly as shown in following example, but it has its own problems which is why Lambda expression was introduced and we will see it in this article:

import java.util.*;

class Book {
    int price;
    String title;

    public Book(int price, String title) {
        this.price = price;
        this.title = title;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Book> books = Arrays.asList(
            new Book(100, "Building Microservices"),
            new Book(200, "Microservices in Action"),
            new Book(50, "Effective Java")
        );

        Collections.sort(books, new Comparator<Book>() {
            @Override
            public int compare(Book b1, Book b2) {
                return b1.price - b2.price;
            }
        });

        for (Book b : books) {
            System.out.println(b.title + " - $" + b.price);
        }
    }
}

The above Java program creates a Book class with two properties: price and title. Then, it creates a list of Book objects, sorts it using a custom Comparator object defined as an anonymous class, and prints the sorted books.

If you look at the code of Anonymous class, you will find that only useful code which method needed was the comparison logic e.g. book1.getPrice()-> book2.getPrice() but you write a lot more code to facilitate that. 

This boiler code makes your code ugly and less readable. Lambda expression solves this problem by removing all that boiler plat and only passing the crux of the code which matter, as shown below.

Other important examples of using Anonymous class in Java are running code on separate thread and handling Events on GUI which I will explain later when I will update this article. 

3 Examples of Anonymous Class to Learn Lambda Expression better in Java 8



Important points about Anonymous class and Lambda expression in Java

Now, let's revise important points about both Anonymous class and Lambda Expression in Java:

1. Like it says, Anonymous class is a class without name i.e. Anonymous, hence it cannot be reused.

2. Anonymous class was one of the way to pass code to a method e.g. Collections.sort() which requires code for comparison, Runnable.run() which requires code to be run on separate thread, and Button.actionPerformed() which requires code to be executed when a button is clicked.

3. Lambda expression makes it easy to pass a block of code to a function by removing all the boiler plate surrounding it due to object-oriented nature of Java programming language. This block of code is also refer as Anonymous function, similar to what JavaScript has.

4. You can also view lambda expression as method e.g. (int x, int y) ->> x + y is a method where left hand side is argument passed to method and right hand side is the code method execute and return the result of computation. 

Since Java is strongly typed language, you can further take out type definition e.g. int, which reduces this lambda expression to x, y->> x + y. The return statement is also omitted as lambda expression implicitly return value.


5. You can use lambda expression instead of Anonymous class in Java 8. This will make your code more expressive, clear and concise. It will also reduce memory footprint of compiled code because a new class will not be created for Anonymous class every time you use them.


That's all about common example of Anonymous class in Java which can be used to learn Lambda expression better. Once you understand what Anonymous class do and why we used it Java e.g. for passing some code to a function, you will immediately realize what lambda expression is doing. This is way better than understanding lambda expression by reading tutorials on syntax and trying to write lambdas. 

Once you understand purpose, syntax will flow naturally to you. Though, Anonymous class was not the only reason lambda expression was introduced, it also help to write functional style code in Java 8. I suggest you to read Java 8 in Action to learn more about motivation behind lambda expression and what it offer to Java world apart from solving the problem of Anonymous class.


Other Java  Tutorials and Articles you may like:
  • The Java Developer RoadMap (see)
  • How to sort the map by keys in Java 8? (example)
  • How to sort the may by values in Java 8? (example)
  • What is the default method in Java 8? (example)
  • How to join String in Java 8 (example)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to use filter() method in Java 8 (tutorial)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • How to use Stream class in Java 8 (tutorial)
  • 10 Courses to learn Java for Beginners (courses)
  • Top 5 courses to become a full-stack Java developer  (courses)
  • How to convert List to Map in Java 8 (solution)
  • Difference between abstract class and interface in Java 8? (answer)
  • Top 5 Courses to learn Functional Programming in Java (courses)
  • 5 Books to Learn Java 8 from Scratch (books)
  • 10 examples of Optional in Java 8? (example)

Thanks for reading this article so far. If you like it then please share with you friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you want to learn Lambda expression in depth and looking for resources then you can also checkout this list of best Lambda Expression and Stream online courses for both beginners and experienced Java developers. In this article, you will find the best online courses on Java Lambda and Stream API from Udemy, Coursera, and other online learning platform.
 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.