A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. Comparator interface is used to sort the objects of a user-defined class. This interface is present in java.util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members.
```
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Student {
String Name;
int Age;
public Student(String Name, Integer Age){
this.Name = Name;
this.Age = Age;
}
public String getName() { return Name; }
public Integer getAge() { return Age; }
@Override public String toString() {
return "{Name=" + Name + ", Age=" + Age + '}';
}
}
class MyComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
int NameCompare = s1.getName().compareTo(s2.getName());
int AgeCompare = s1.getAge().compareTo(s2.getAge());
return (NameCompare == 0) ? AgeCompare : NameCompare;
}
}
class Main {
public static void main(String[] args) {
List<Student> al = new ArrayList<>();
al.add(new Student("E", 22));
al.add(new Student("A", 23));
Collections.sort(al, new MyComparator());
for (Student s : al) {
System.out.println(s);
}
}
}
```