Comparator in Java

What is Comparator interface in Java?

The Comparator interface in Java is part of the Collection Framework, and we use it to sort objects.

In the last tutorial, we saw how we could use the Comparable interface to sort custom objects based on one field.

Using the Comparator interface, we can have multiple sort choices and sort objects based on any choice.

This interface is found in Java.util package and contains two methods:

  • public int compare(Object obj1, Object obj2) – Compares the first object with the second object.
  • public boolean equals(Object obj) – Compares the current object with the specified object


Ordering the custom objects using Comparator interface – example

First, we create a custom class – User

class User {
  public int userId;
  public String username;
  public String address;
 
  public User(int userId, String username, String address) {
    this.userId = userId;
    this.username = username;
    this.address = address;
  }
 
}


We create a UserIdComparator class that defines comparison logic based on the userId field. It implements the Comparator interface and returns 1 if the userId of the first object is greater than the second, 0 if both userId fields are equal, and -1 if the userId field of the first object is less than the second object.

class UserIdComparator implements Comparator<User> {

  public int compare(User user1, User user2) {
    if (user1.userId == user2.userId) {
      return 0;
    } else if (user1.userId > user2.userId) {
      return 1;
    } else {
      return -1;
    }
  }
}


Now we create a UsernameComparator class that defines comparison logic based on the username field. It also implements the Comparator interface, and since we are comparing Strings, we can use the compareTo() method of String class, instead of writing our own logic for comparing the values.

class UsernameComparator implements Comparator<User> {

  public int compare(User user1, User user2) {
    return user1.username.compareTo(user2.username);
  }

}


We create a Test class where we put the logic for actual sorting by calling the Collections.sort method and passing the Comparator class:

class Test {

    public static void main(String[] args) {

      List<User> users = new ArrayList<>();

      users.add(new User(5, "username4", "Address1"));
      users.add(new User(2, "username1", "Address2"));
      users.add(new User(7, "username2", "Address3"));
      users.add(new User(3, "username5", "Address4"));

      System.out.println("Before sorting:");

      for (User user : users) {
        System.out.println(user.userId + " " + user.username + " " + user.address);
      }

      // Sorting by userId field
      Collections.sort(users, new UserIdComparator());

      System.out.println("After sorting by userId field:");

      for (User user : users) {
        System.out.println(user.userId + " " + user.username + " " + user.address);
      }

      // Sorting by username field
      Collections.sort(users, new UsernameComparator());

      System.out.println("After sorting by username field:");

      for (User user : users) {
        System.out.println(user.userId + " " + user.username + " " + user.address);
      }
    }
}
Output: Before sorting: 5 username4 Address1 2 username1 Address2 7 username2 Address3 3 username5 Address4 After sorting by userId field: 2 username1 Address2 3 username5 Address4 5 username4 Address1 7 username2 Address3 After sorting by username field: 2 username1 Address2 7 username2 Address3 5 username4 Address1 3 username5 Address4
 
That’s it!

Leave a Reply

Your email address will not be published.