Sorting Custom Object by Implementing Comparable Interface in Java
Java provides two interfaces to sort objects using data members of the class which are Comparable and Comparator. In this article, we will focus on a Comparable interface. A Comparable object is capable of comparing itself with another object by natural ordering. The class must implement the java.lang.Comparable interface to compare its instances.
Using Comparable interface we can sort:
- String objects
- Wrapper class objects
- User-defined objects
Syntax
public interface Comparable<T> { public int compareTo(T o); }
Where T is the type of Object to be sorted.
compareTo() method
For any class to support sorting, it should implement the Comparable interface and override it’s compareTo() method. It returns a negative integer if an object is less than the specified object, returns zero if an object is equal, and returns a positive integer if an object is greater than the specified object.
Example 1: Sort the given data according to the student marks.
Java
// Java program to sort student // data according to their marks import java.util.*; // implementing comparable interface class StudentData implements Comparable<StudentData> { String name; int marks; // Constructor StudentData(String name, int marks) { this .name = name; this .marks = marks; } // overriding method to sort // the student data public int compareTo(StudentData sd) { return this .marks - sd.marks; } } // Driver class class GFG { public static void main(String[] args) { ArrayList<StudentData> list = new ArrayList<StudentData>(); // Inserting data list.add( new StudentData( "Ram" , 98 )); list.add( new StudentData( "Shyam" , 84 )); list.add( new StudentData( "Lokesh" , 90 )); Collections.sort(list); // Displaying data for (StudentData sd : list) System.out.println(sd.name + " " + sd.marks); } } |
Shyam 84 Lokesh 90 Ram 98
Example 2: Sort the given data according to the names.
Java
// Java program to sort student // data according to their names import java.util.*; // implementing comparable interface class StudentData implements Comparable<StudentData> { int roll; String name; int marks; // Constructor StudentData( int roll, String name, int marks) { this .roll = roll; this .name = name; this .marks = marks; } // overriding method to sort // the student data public int compareTo(StudentData sd) { // compareTo is a string method return this .name.compareTo(sd.name); } } // Driver class class GFG { public static void main(String[] args) { ArrayList<StudentData> list = new ArrayList<StudentData>(); // Inserting data list.add( new StudentData( 1 , "Ram" , 98 )); list.add( new StudentData( 2 , "Shyam" , 84 )); list.add( new StudentData( 3 , "Lokesh" , 90 )); Collections.sort(list); // Displaying data for (StudentData sd : list) System.out.println(sd.roll + " " + sd.name + " " + sd.marks); } } |
3 Lokesh 90 1 Ram 98 2 Shyam 84