How to Sort Wrapper class Collection in Apex

There is inbuilt functionality in Apex to sort the primitive datatypes supported by 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

But think, How 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 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 {

	//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;

Book.sortBy = Book.SORT_BY.ByPrice;

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


14 responses to “How to Sort Wrapper class Collection in Apex”

  1. DP Avatar

    Hi , I am not able to understand how is the method returning compare To results ?

    1. JitendraZaa Avatar

      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.

  2. mar1B Avatar

    does anybody tried to cover 100% of this sample code while testing?

  3. gajendra Avatar

    This article is very nice

  4. Zaidy Ramirez Avatar

    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.

  5. Aravind Avatar

    Thanks dude. It is good peace of code.

  6. Aravind Avatar

    Is there any way that we can specify sorting order like ascending or descending order?

    1. JitendraZaa Avatar


      Its upto you how you return the value in method “compareTo”.

      Just change the logic and go..

  7. VN Avatar

    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 {

    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. JitendraZaa Avatar

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

      Please post complete code.

  8. krishna Avatar

    can any one will please do this VF page controller, if any question please ask me about this VF page

  9. mike Avatar

    How can this be changed to descending order?

  10. Harshad Avatar

    what if I want to compare by both i.e 1st price and then name

    1. test87 Avatar

      How the date compare to is going to work here, lets say if i want to compare by publishingDate ?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading