Many links are changed in javatpoint. If any link is not working, please delete the cookie of your browser and refresh the page.

91-9990449935

 0120-4256464

Comparator interface

Comparator interface is used to order the objects of user-defined class.

This interface is found in java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).

It provides multiple sorting sequence i.e. you can sort the elements based on any data member. For instance it may be on rollno, name, age or anything else.

Syntax of compare method

public int compare(Object obj1,Object obj2): compares the first object with second object.


Collections class provides static methods for sorting the elements of collection. If collection elements are of Set type, we can use TreeSet. But We cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list,Comparator c): is used to sort the elements of List by the given comparator.


Example of sorting the elements of List that contains user-defined class objects on the basis of age and name

In this example, we have created 4 java classes:

  1. Student.java
  2. AgeComparator.java
  3. NameComparator.java
  4. Simple.java
Student.java

This class contains three fields rollno, name and age and a parameterized constructor.

AgeComparator.java

This class defines comparison logic based on the age. If age of first object is greater than the second, we are returning positive value, it can be any one such as 1, 2 , 10 etc. If age of first object is less than the second object, we are returning negative value, it can be any negative value and if age of both objects are equal, we are returning 0.

NameComparator.java

This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic.

Simple.java

In this class, we are printing the objects values by sorting on the basis of name and age.

Output:Sorting by Name...
       106 Ajay 27
       105 Jai 21
       101 Vijay 23
       Sorting by age...       
       105 Jai 21
       101 Vijay 23
       106 Ajay 27