Comparable Interface in Apex

Author - Webner

When we have to sort a custom object list, based on a field, we try doing it by SOQL query ORDER BY but sometimes due to any constraint or some complex requirements we need to sort the list in Apex itself, then we have Sort method but that also does not allow us to sort the list with respect to a particular custom field. So, we have another method with which we can do the sorting and customize it with the requirement at hand.

If we need to sort the list for non-primitive types then we can use the Comparable interface which would add sorting support for Lists of user-defined types, with the help of the compareTo method of the aforementioned interface.

This method returns integer values as follows when compared to other records of the same object.

  • 0 is returned when both records are equal
  • 1 is returned when the instance is greater than the compareToObject
  • -1 is returned when the instance is less than the compareToObject

public class Student implements Comparable {
public Integer Id {get; set; }
public String Name {get; set; }
public Decimal Percentage {get; set; }
public Student(Integer i, String n, Decimal p) { = i; = n;
this.percentage = p;
public Integer compareTo(Object objToCompare) {
Student stu= (Student)objToCompare;
if ( == stu.Id){
return 0;
else if ( > stu.Id && this.percentage > stu.Percentage){
return 1;
return -1;

This can also be done by passing the whole object and not the specific fields and can also work for wrappers.
public class sortData implements Comparable {
public Custom_Object__c objData {get; set; }
public sortData(Custom_Object__c obj){
this.objData = obj;
public Integer compareTo(Object compareTo){
sortData compareToData = (sortData)compareTo;
Integer returnValue = 0;
if(!String.isBlank(this.objData.Field__c)) {
if(this.objData.Field__c < compareToData.objData.Field__c){
returnValue = 1;
else if(this.objData.Field__c > compareToData.objData.Field__c){
returnValue = -1;
return returnValue;

This can be invoked by a simple call using the sort method on that particular list of objects.
List<Student> stuList = new List<Student>();
stuList.add(new Student(104,'Aakash', 80.55));
stuList.add(new Student(102,'Aditya', 90.75));
stuList.add(new Student(103,'Anshul', 93.50));
stuList.add(new Student(101,'Rohan', 78.50));
//Sort using the custom compareTo() method

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published.