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
import java.util.*;
class StudentData implements Comparable<StudentData> {
String name;
int marks;
StudentData(String name, int marks)
{
this .name = name;
this .marks = marks;
}
public int compareTo(StudentData sd)
{
return this .marks - sd.marks;
}
}
class GFG {
public static void main(String[] args)
{
ArrayList<StudentData> list
= new ArrayList<StudentData>();
list.add( new StudentData( "Ram" , 98 ));
list.add( new StudentData( "Shyam" , 84 ));
list.add( new StudentData( "Lokesh" , 90 ));
Collections.sort(list);
for (StudentData sd : list)
System.out.println(sd.name + " " + sd.marks);
}
}
|
Output
Shyam 84
Lokesh 90
Ram 98
Example 2: Sort the given data according to the names.
Java
import java.util.*;
class StudentData implements Comparable<StudentData> {
int roll;
String name;
int marks;
StudentData( int roll, String name, int marks)
{
this .roll = roll;
this .name = name;
this .marks = marks;
}
public int compareTo(StudentData sd)
{
return this .name.compareTo(sd.name);
}
}
class GFG {
public static void main(String[] args)
{
ArrayList<StudentData> list
= new ArrayList<StudentData>();
list.add( new StudentData( 1 , "Ram" , 98 ));
list.add( new StudentData( 2 , "Shyam" , 84 ));
list.add( new StudentData( 3 , "Lokesh" , 90 ));
Collections.sort(list);
for (StudentData sd : list)
System.out.println(sd.roll + " " + sd.name + " "
+ sd.marks);
}
}
|
Output
3 Lokesh 90
1 Ram 98
2 Shyam 84
Last Updated :
28 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...