Comparable in Java - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Comparable is an interface in Java and it comes from java.lang package. This interface is used to compare objects in a class and sorts them according to the natural/reversed order. Hence by using this interface we can sort an array of custom objects.
Lists and arrays of objects that implement Comparable interface can be sorted automatically by Collections.sort() and Arrays.sort() methods. The object will be arranged depending upon the co­mpareTo() method available in the implemented class. Let us discuss the Comparable interface in detail with examples in this tutorial.
Using Comparable interface we can sort :

String objects
Wrapper class objects
User-defined class objects

String objects
Wrapper class objects
User-defined class objects
public int compareTo(Object o);
This method compares the object for the specified object for order. It returns the below values when comparing the object corresponding to 3 cases as:
Firstly, if the first element is less than the second element it returns “-1′′.
In the case that the first element equals to the second element, it returns “0”.
The last case in which the first element is greater than the second element, it returns “1”.
For example, we are going to sort the Students’ age in the Student object using the comparable interface and compareTo() method.
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 program ComparableDemo.java for accessing the student class.
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");
        }
    }
}
23
24
30
35
Let us see the same example shown above with a small change. As a result, sorting will be done on the age in reverse order.
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;
        }
    }
}
In the above program ‘Comparable2.java’, we did a small correction compared to the ‘Comaparable.java’. That is we changed the condition from age>student.age to age<student.age which returns 1 if the first element is less than the second element. Therefore we get the students’ age in the reverse order. Now, we create a program ‘ComparableDemo2.java’ same as the ‘Comparable.java’ without any change for accessing the student class.
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");
        }
    }
}
35
30
24
23
Hence, we can see that the age given in the list is sorted in reverse order. To sum up, for comparing single bean properties we can use the Comparable interface and override the method compareTo(Object o).
Happy Learning 🙂

Comparator vs Comparable in Java
Comparator in Java
User defined sorting with Java 8 Comparator
String sorting in Java
Java 8 Getting Min and Max values from a Stream
Hibernate Filter Example Xml Configuration
Hibernate Native SQL Query Example
ArrayList in Java
How HashMap Works In Java
What are Lambda Expressions in Java 8
Collection Framework & Collection Interfaces in Java
Java Class Example Tutorials
Java 8 Stream Filter Example with Objects
Java variable types Example
Lambda Expressions in Java

Comparator vs Comparable in Java
Comparator in Java
User defined sorting with Java 8 Comparator
String sorting in Java
Java 8 Getting Min and Max values from a Stream
Hibernate Filter Example Xml Configuration
Hibernate Native SQL Query Example
ArrayList in Java
How HashMap Works In Java
What are Lambda Expressions in Java 8
Collection Framework & Collection Interfaces in Java
Java Class Example Tutorials
Java 8 Stream Filter Example with Objects
Java variable types Example
Lambda Expressions in Java
 


Δ
 Install Java on Mac OS
 Install AWS CLI on Windows
 Install Minikube on Windows
 Install Docker Toolbox on Windows
 Install SOAPUI on Windows
 Install Gradle on Windows
 Install RabbitMQ on Windows
 Install PuTTY on windows
 Install Mysql on Windows
 Install Hibernate Tools in Eclipse
 Install Elasticsearch on Windows
 Install Maven on Windows
 Install Maven on Ubuntu
 Install Maven on Windows Command
 Add OJDBC jar to Maven Repository
 Install Ant on Windows
 Install RabbitMQ on Windows
 Install Apache Kafka on Ubuntu
 Install Apache Kafka on Windows
 Java8 – Install Windows
 Java8 – foreach
 Java8 – forEach with index
 Java8 – Stream Filter Objects
 Java8 – Comparator Userdefined
 Java8 – GroupingBy
 Java8 – SummingInt
 Java8 – walk ReadFiles
 Java8 – JAVA_HOME on Windows
 Howto – Install Java on Mac OS
 Howto – Convert Iterable to Stream
 Howto – Get common elements from two Lists
 Howto – Convert List to String
 Howto – Concatenate Arrays using Stream
 Howto – Remove duplicates from List
 Howto – Filter null values from Stream
 Howto – Convert List to Map
 Howto – Convert Stream to List
 Howto – Sort a Map
 Howto – Filter a Map
 Howto – Get Current UTC Time
 Howto – Verify an Array contains a specific value
 Howto – Convert ArrayList to Array
 Howto – Read File Line By Line
 Howto – Convert Date to LocalDate
 Howto – Merge Streams
 Howto – Resolve NullPointerException in toMap
 Howto -Get Stream count
 Howto – Get Min and Max values in a Stream
 Howto – Convert InputStream to String