Comparable in Java

What is a Comparable in Java?

A Comparable in Java is an interface, and it is mainly used to sort the arrays or lists of custom objects. It contains only one method: compareTo(Object).
Using the compareTo method, we can sort the elements based on the single data member only.

Comparable compareTo() method

The syntax is:

 public int compareTo(Object obj)

It is used to compare the current object with the specified object. It returns:

  • zero, if the current object is equal to the specified object.
  • a positive integer, if the current object is greater than the specified object.
  • negative integer, if the current object is less than the specified object.

String and Wrapper classes already implement the Comparable interface, and we can use Collections.sort or Arrays.sort methods to sort the list or array.

Sorting the list of strings in Java using Collections.sort() method

Example:

class Test {

  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("Python");
    list.add("Java");
    list.add("JavaScript");
    list.add("Ruby");
    list.add("Kotlin");

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

    // sorting the list
    Collections.sort(list);

    System.out.println("After sorting:");
    System.out.println(list);
  }
}
Output: Before sorting: [Python, Java, JavaScript, Ruby, Kotlin] After sorting: [Java, JavaScript, Kotlin, Python, Ruby]

Sorting the array of Integers in Java using Arrays.sort() method

Note: int is automatically converted to its Wrapper class – Integer.

Example:

class Test {

  public static void main(String[] args) {
    int[] array = {7, 9, 2, 1, 5};

    System.out.println("Before sorting:");
    System.out.println(Arrays.toString(array));

    //sorting the array
    Arrays.sort(array);

    System.out.println("After sorting:");
    System.out.println(Arrays.toString(array));
  }
}
Output: Before sorting: [7, 9, 2, 1, 5] After sorting: [1, 2, 5, 7, 9]

Sorting Custom objects by implementing a Comparable interface

If we want to sort the objects of the custom class then the class needs to implement a Comparable interface.
Example:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class User implements Comparable<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;
  }

  @Override
  public int compareTo(User user) {

    if (this.userId == user.userId) {
      return 0;
    } else if (this.userId > user.userId) {
      return 1;
    } else {
      return -1;
    }
  }
}

class Test {

  public static void main(String[] args) {

    List<User> users = new ArrayList<>();
        
    users.add(new User(5, "username1", "Address1"));
    users.add(new User(2, "username2", "Address2"));
    users.add(new User(7, "username3", "Address3"));
    users.add(new User(3, "username4", "Address4"));

    Collections.sort(users); // it will sort the users based on the userId field

    for (User user : users) {
      System.out.println(user.userId + " " + user.username + " " + user.address);
    }
  }
}
Output: 2 username2 Address2 3 username4 Address4 5 username1 Address1 7 username3 Address3
 
Here, we created a custom class User, which implements the Comparable interface. It inherited the compareTo method, and we wrote the code inside it to return 0 if the values of the userId field are equal, 1 if the value of the current object is greater than the passed object, and-1 if the userId value of the current object is smaller than the passed object.
 
Since the User class implements the Comparable interface, we were able to use the Collections.sort method. And so, we sorted the users based on the userId field.
 
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *