What is the best way to learn lambda expression of Java 8? Of course by using it on your day to day programming task. Since implementing equals, hashcode, compareTo, and compare methods are some of the most common task of a Java developer, it make sense to learn how to use lambda expression to implement custom Comparator and Comparable in Java. One question comes in mind, can we use lambda expression with Comparator, because it's an old interface and may not implement functional interface annotated with
@FunctionalInterface annotation? Answer to this question is Yes, you can use lambda expression to implement Comparator and Comparable interface in Java, and not just these two but to implement any interface, which just got one abstract method, remember from Java 8 interface can have non abstract methods as well e.g.
default and
static methods. That's why lambda expression in Java 8 is known as SAM type, where SAM stands for Single Abstract Method. This was a very important decision Java designers made, which makes it lambdas even more useful. Due to this you can use lambda expressions with Runnable, ActionListener and several other interface which got just one abstract method. By the way, you need not to worry in case of Comparator, because it is made to implement
@FunctionalInterface as shown below :