Understanding Comparator Interface

Let's discuss the working of Comparator Interface.

One of the major drawbacks of using a Comparable interface is that the comparing logic gets fixed. For instance, if we have a Vehicle class, then it can be sorted either on the basis of the brand or the production year depending on the implementation of the compareTo() method.

If we need some flexibility in sorting, we should use the Comparator interface instead of the Comparable interface. The Comparator interface has a method, compare(T o1, T o2), which takes two objects, o1 and o2 as parameters. It returns -1 if o1 << o2, 1 if o1 >> o2 and 0 if o1 is equal to o2.

If we need to use the Comparator interface, then we can’t use the Collections.sort(List<T> t) method as T should implement the Comparable interface. There is another overloaded method, sort(List<T> list, Comparator<? super T> c), that takes the list as well as a Comparator object as input. It then sorts the List on the basis of logic, which is provided in the Comparator implementation.

The below code shows how to create a custom Comparator. We will create two custom comparators: one for sorting by brand and one for sorting by year.

Get hands-on with 1200+ tech skills courses.