Before Lambda, Anonymous class was used to implement these one method interfaces. After Java 8, lambdas can be used instead of an anonymous class to avoid boilerplate code.
How to implement Comparator in Java 8 using lambdas?
Java program to implement Comparator using the lambda expression in Java 8:
In this example, we have an object called Books with two attributes title and price, where the title is String and price is BigDecimal because float and double are not good for exact calculations.
Now we have a list of Book and our task is to sort based on their price or based upon their title. To complete these task, we need to create two custom Comparator implementation, one to sort Books by title and other to sort it by price.
To show the stark difference in the number of lines of code you need to do this prior to Java 8 and in JDK 1.8, we have implemented that two Comparator first using Anonymous class and later using the lambda expression and can see that lambdas based Comparator just take one line.