Renewed Comparator: Everything You Should Know
Explore the enhanced Comparator interface in Java 8, including new static and default methods that simplify sorting collections. Learn how to use comparing, thenComparing, naturalOrder, reverseOrder, nullsFirst, and nullsLast for more concise and flexible sorting logic with lambdas.
Introduction to the Comparator interface
Comparator is an interface that is used to define how a collection must be sorted. In Java 7, it had just 2 methods – compare() and equals(). The enhanced Comparator in Java 8 now has 19 methods.
However, the Comparator is still a functional interface as it has only one abstract method, i.e., compare().
Comparator now supports declarations via lambda expressions as it is a Functional Interface. We saw this in our lambda expressions chapter as well. Below is the list of methods in the Comparator interface.
We will look at how these new methods work and discuss the functionalities they ...