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.
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.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);
}
}
}
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.
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.
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.
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.
- 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)
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.