Tutorials

Java Collection Framework


Comparator Interface


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:

  1. compare(Object object1, Object object2)
  2. equals(Object obj)

 

 

 

 

 



Please Share this page
Views : 77
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!