Just like comparable interface, comparator interface is also used to sort the user-defined objects.
Comparator interface has upper hand over Comparable interface in case you have to go for multiple sorting sequence. It means we can sort any collection based on multiple attributes. Moreover, using Comparator interface doesn’t force you to change the actual Class while sorting.
When using Collections.sort() you will find two sort methods:
Collections.sort(List list) // List objects must be of comparable type
Collections.sort(List list, Comparator c)
We have already learned about the first method in Comparable interface chapter. Click to read again
Second method is what we are going to focus on in this chapter.
Comparator interface has two methods:
compare(Object object1, Object object2)