The Comparator interface is used to define custom ordering of elements in a collection. By default, the ordering is based on the natural ordering of the elements (using the Comparable interface), but sometimes we need to sort elements based on a specific attribute or a custom rule that is not the natural ordering.
The Comparator interface defines two methods: compare() and equals(). The compare() method takes two objects as arguments and returns an integer value indicating their ordering. The equals() method checks whether the specified object is equal to the Comparator object.
To use a Comparator, we need to create a class that implements the Comparator interface and override the compare() method. We can then pass an instance of this class to the appropriate sort method, such as Collections.sort() or Arrays.sort().
Here is an example of how to use the Comparator interface to sort a list of Person objects based on their age:
import java.util.*;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class AgeComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
}
public class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 25));
people.add(new Person("Bob", 20));
people.add(new Person("Charlie", 30));
System.out.println("Before sorting: " + people);
Collections.sort(people, new AgeComparator());
System.out.println("After sorting by age: " + people);
}
}
In this example, we have defined a Person class with a name and age field. We have also defined an AgeComparator class that implements the Comparator interface and overrides the compare() method to compare Person objects based on their age.
In the main method, we create a list of Person objects and print it out before and after sorting by age using the Collections.sort() method and passing an instance of the AgeComparator class as a parameter.
Output:
Before sorting: [Person{name='Alice', age=25}, Person{name='Bob', age=20}, Person{name='Charlie', age=30}]
After sorting by age: [Person{name='Bob', age=20}, Person{name='Alice', age=25}, Person{name='Charlie', age=30}]
As we can see from the output, the list is sorted based on the age field of the Person objects.
In summary, the Comparator interface is used to define custom ordering of elements in a collection, and we implement it by creating a class that implements the Comparator interface and overrides the compare() method. We can then pass an instance of this class to the appropriate sort method to sort the collection based on the custom ordering.