What is comparator Interface in Java with Examples?

The comparison interface is used to sort objects of user-defined classes. The comparator object can compare two objects of two different classes. The following function compares obj1 with obj2

In Java, the Comparator interface is used to define custom sorting orders for objects that do not have a natural ordering. This interface contains a single method called compare, which takes two objects as arguments and returns an integer value based on the comparison of the objects.

Here is an example of how to use the Comparator interface to sort a list of strings in reverse alphabetical order: 

 

List strings = Arrays.asList("apple", "banana", "orange", "pear");

Comparator reverseAlphabeticalComparator = new Comparator() {
    @Override
    public int compare(String s1, String s2) {
        return s2.compareTo(s1);
    }
};

Collections.sort(strings, reverseAlphabeticalComparator);
System.out.println(strings); // [pear, orange, banana, apple]

In this example, we define a new Comparator object that implements the compare method to return the result of s2.compareTo(s1), which sorts the strings in reverse alphabetical order. We then pass this Comparator object to the sort method of the Collections class to sort the list of strings.

The Comparator interface can be used to sort objects of any class, as long as the objects can be compared using a consistent set of rules. This makes it a powerful tool for custom sorting in Java.

Submit Your Programming Assignment Details