How to Sort Wrapper class Collection in Apex

Author posted by Jitendra on Posted on under category Categories Apex, Salesforce and tagged as Tags , with 12 Comments on How to Sort Wrapper class Collection in Apex

There is inbuilt functionality in Apex to sort the primitive datatypes supported by force.com. I am sure maximum of developers must have come across the situations where they need to sort custom datatype built by them i.e. custom class or I would say wrapper class in terms of force.com.

But think, How force.com will come to know that how to sort class? In case of integer, date or double they already know. But how they are going to know that what is going to be content in your class? Before Summer’12 there was no direct way. However thanks to Salesforce to introduce the interface Comparable in Summer’12 release. And… there is smile on the face of Java developers, because they already know what it is.

So let’s start with “What is the use of interface Comparable?“ I would say, this is the way to tell force.com that how we are going to compare the custom Objects (Wrapper class).

Comparable Interface:

To implement the Comparable Interface, you must declare global class with the implements keyword as follow:

global class Book implements Comparable

Now, your class must implement the method “compareTo“ as follow:

global  Integer compareTo(Object objToCompare)
{
	//Your code to implement logic
}

compareTo() method:

The compareTo() method must return following integer value

  1. 0 if both object is equal
  2. >0 if the instance object is greater than “objToCompare”
  3. <0 if the instance object is smaller than “objToCompare”

Sample code
Let’s take the example of class “Book”, which have following data members,

  • BookTitle – String
  • Author – String
  • TotalPages – Integer
  • Price – Double
global class Book implements Comparable {

	public String BookTitle ;
	public String Author ;
	public Integer TotalPages ;
	public Double Price ;
	public Date publishingDate;

	public enum SORT_BY {
		ByTitle,ByPage
		}

	//Variable to decide the member on which sorting should be performed
	public static SORT_BY sortBy = SORT_BY.ByTitle;

	public Book(String bt, String a, Integer tp, Double p, Date pd)
	{
		BookTitle = bt;
		Author = a;
		TotalPages = tp;
		Price = p;
		publishingDate = pd;
	}

	global Integer compareTo(Object objToCompare) {
		//Sort by BookName Alphabetically
		if(sortBy == SORT_BY.ByTitle)
		{
			return BookTitle.compareTo(((Book)objToCompare).BookTitle);
		}
		else //Sort by Book price
		{
			return Integer.valueOf(Price - ((Book)objToCompare).Price);
		}
	}
}

As you can see in above code, we are sorting on the basis of either BookTitle or Price. The logic can be anything depending on business requirement.

Running the sample code in Developer Console:
Run below code in “Developer Console” from browser or “Execute Anonymous” from Eclipse.

Book[] books = new Book[]{
	new Book('Salesforce Handbook','Jeff Douglas',360,35,Date.newInstance(2011, 03, 20)),
	new Book('Let Us C','Yashavant P. Kanetkar',593,58,Date.newInstance(2008, 03, 21)),
	new Book('Head First Design Patterns ','Elisabeth Freeman',678,28,Date.newInstance(2004, 11,01))
};

Book.sortBy = Book.SORT_BY.ByTitle;
books.sort();
System.debug(books);

Book.sortBy = Book.SORT_BY.ByPrice;
books.sort();
System.debug(books);

When you will see the output, first time it sorted by BookTitle and second time it is sorted according Price.
I hope this post will be helpful to many salesforce developers.
Happy coding!!!

Related posts

12 thoughts on “How to Sort Wrapper class Collection in Apex”

    1. Hi, For string we already have compare to methods which returns either 0, 1. In case of integers we are handling those value by our self only.

  1. Thank you for this, it is very useful. Any chance to pick your brain on how to sort by two wrapper properties? so first BookTitle, then BookPrice… any comments would be appreciated.

  2. Hi Jitendra,

    Can u please guide me … I have followed the steps for wrapper sorting and its working great in a table doen’t have any null values… but in my table having null values for few columns then its giving errors… Please see my piece of code.

    global with sharing class ActivitiesCollection implements Comparable {
    public string type{get;set;}
    }

    public enum SORT_BY {
    ByType
    }

    public enum Order_By{
    ascend, descend
    }
    global integer compareTo(Object objToCompare) {
    if (typo != null && typo != ” && type != null && type != ” && sortBy ==SORT_BY.ByType && orderBy == Order_BY.ascend)
    return type.compareTo(typo);
    else if (typo != null && typo != ” && type != null && type != ” && typo != ‘–None–‘ && sortBy ==SORT_BY.ByType && orderBy == Order_BY.descend)
    }
    return typo.compareTo(type);

    }

    Please help me.

    1. Hi ,
      Above code is not complete. What is typo and how you are comparing object “objToCompare” ?

      Please post complete code.

Leave a Reply