Comparable & Comparator in Java

Upasana | November 21, 2020 | 3 min read | 1,469 views


Java provides two mechanisms to compare objects:

  1. Using Comparable interface

  2. Using Comparator interface

The purpose for using one of these interface depends upon the usecase. We will discuss both the approaches one by one.

Using Comparable Interface

When we implement comparable interface in a class, it imposes a total ordering on its objects. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method.

Following is the definition for this interface.

Comparable.java
public interface Comparable<T> {

    public int compareTo(T o);

}

Few important points:

  1. Lists of objects that implement this interface can be sorted automatically by Collections.sort or Arrays.sort

  2. Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without need to specify a comparator.

Example

Person class with Natural ordering based on name
class Person implements Comparable<Person>{
    int age;
    String name;
    String email;

    @Override
    public int compareTo(Person o) {
        return name.compareTo(o.getName());
    }
}

Now we can sort a collection of persons based on its natural ordering using Collections.sort method.

Sorting in Natural Order
List<Person> students = Arrays.asList(
        new Person(20,"Bob", "bob@mail.com"),
        new Person(19, "Jane", "Jane@mail.com"),
        new Person(21,"Foo", "foo@mail.com")
);
Collections.sort(students);
Program output (sorting based on person’s name)
Bob
Foo
Jane

Using Comparator Interface

A comparison function, which imposes a total ordering on some collection of objects.

Comparator.java
@FunctionalInterface
public interface Comparator<T> {

    int compare(T o1, T o2);

}
  1. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. We can have more than one Comparator for a given class, for example Person class may have two different comparators, one that sorts based on name and another based on age.

  2. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.

Example

Lets define two comparators now, one for name based comparison and another on basis of age.

NameComparator & AgeComparator
class NameComparator implements Comparator<Person> {

    @Override
    public int compare(Person o1, Person o2) {
        return o1.name.compareTo(o2.name);
    }
}

class AgeComparator implements Comparator<Person> {

    @Override
    public int compare(Person o1, Person o2) {
        return ((Integer)o1.age).compareTo(o2.age);
    }
}

Now we can specify one of the above defined sorting function to choose sorting on demand:

Soritng based on Age
List<Person> students = Arrays.asList(
        new Person(20,"Bob"),
        new Person(19, "Jane"),
        new Person(21,"Foo")
);
Collections.sort(students, new AgeComparator());

Similarly, we can sort based on NameComparator as well.

Java 8 style comparator using lambda approach

Java 8’s lambda can be used to write inline comparator and even chain them as and when required.

Comparing by name and then age (if name is same)
List<Person> students = Arrays.asList(
        new Person(20,"Foo"),
        new Person(19, "Jane"),
        new Person(21,"Foo")
);
Collections.sort(students);
students.stream()
        .sorted(Comparator
                .comparing(Person::getName)
                .thenComparing(Person::getAge)
        ).forEach(System.out::println);

That’s all for this article.


Top articles in this category:
  1. Java Coding Problems for SDET Automation Engineer
  2. 50 Java Interview Questions for SDET Automation Engineer
  3. Junit interview questions for SDET automation engineer
  4. Rest Assured API Testing Interview Questions
  5. Difference between Enumeration and Iterator in Java
  6. Anagrams string checker in Java
  7. JUnit 5 Parameterized Tests

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.