Comparator interface lies in java.util package. It is used to short object in defined order i.e. sort two objects based on defined criteria.

The compare(Object o1, Object o2) method of Comparator interface needs to be implemented for this purpose, which compares two objects and returns an integer, depending on the comparison.

Decision can be taken based on below returned value:

  • +VE = If o1 is greater than o2.
  • -VE = If o1 is less than o1.
  • 0 VE = If o1 equals to o2.

You need to call compare() method if you are comparing objects. Prefer relational operator over arithmetic operator for comparing numeric fields for better performance.

The compare Method

By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison.

Example of Comparator:


List of unsorted languages:[ComputerLanguage [name=Java, complexity=9], ComputerLanguage [name=C, complexity=10], ComputerLanguage [name=C++, complexity=10], ComputerLanguage [name=Python, complexity=7], ComputerLanguage [name=PHP, complexity=5]] List of sorted languages by name:[ComputerLanguage [name=C, complexity=10], ComputerLanguage [name=C++, complexity=10], ComputerLanguage [name=Java, complexity=9], ComputerLanguage [name=PHP, complexity=5], ComputerLanguage [name=Python, complexity=7]] List of sorted languages by complexity:[ComputerLanguage [name=PHP, complexity=5], ComputerLanguage [name=Python, complexity=7], ComputerLanguage [name=Java, complexity=9], ComputerLanguage [name=C, complexity=10], ComputerLanguage [name=C++, complexity=10]]
Reference Docs:

Oracle Comparator Reference

Leave a Reply

Your email address will not be published. Required fields are marked *