Comparable in Java is an interface, it is coming from java.lang package. If any class includes Comparable interface then group of that Objects can be arranged automatically using either Arrays.sort() or Collection.sort(). Object will be arranged depending upon the co­mpareTo method available in implemented class. Objects that includes comparable in­ java can be employed as a keys in a SortedSet like TreeSet or SortedMap like TreeMap without including any other interface.

Methods in Comparable Interface

public int compareTo(Object o);

The method compares the object for the specified object for order. It returns the below values when comparing the object.

In the case of first element less than of second element  it returns   “-1″;

In the case of first element equals to second element, it returns   “0”;

In the case of first element greater than of second element, it returns   “1”;

Comparable Example

In the bellow example we are going to sort the Student object with respect to the Student ID.

Comparable.java
class Student implements Comparable < Student > {
    int id;String name;String regNumber;int age;String gender;public Student(int id, String name, String regNumber, int age, String gender) {
        this.id = id;
        this.name = name;
        this.regNumber = regNumber;
        this.age = age;
        this.gender = gender;
    }
    @Override public int compareTo(Student student) {
        if (age == student.age) {
            return 0;
        } else if (age > student.age) {
            return 1;
        } else {
            return -1;
        }
    }
}

Creating a ComparableDemo.java for accessing the student class.

ComparableDemo.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; 
public class ComparableDemo {
    public static void main(String[] args) {
        List < Student > list = new ArrayList < Student > ();
        list.add(new Student(1, "ChandraShekhar", "2015011501", 24, "M"));
        list.add(new Student(2, "John", "5623521", 35, "M"));
        list.add(new Student(3, "Smith", "986623", 30, "M"));
        list.add(new Student(4, "Joi", "856421", 23, "F"));
        Collections.sort(list);
        int size = list.size();
        for (int i = 0; i < size; i++) {
            Student student = list.get(i);
            System.out.print(student.age + " \n");
        }
    }
}

Output

Terminal
23
24
30
35

It is recommended that, For comparing the single bean properties we can use the Comparable interface and override the compareTo(Object o).

Happy Learning 🙂