Press ESC to close

Salesforce summer’12 Sorting enhancements reviewed !

With summer’12 release, I was very happy to see the ability to sort Non-primitive data types in apex with availability of List.sort() and Comparable fixture. Having native or system sorting support is great, but few gaps are their as well.

Goodness !

  • One no more needs to use hacks of creating primitive string keys for UDT(User Defined Types) and giving sorting support, this post shows one such hack.

  • Lesser consumption of script statements: As sorting will be done by native API, script statements wasted in comparisons and looping will not be counted in. But, please be careful with “compareTo” method implementation, code in that method will add to script lines consumption during sorting operation. So if you are sorting a big collection, please keep eye on compareTo() method.


  • Sortable Class should be Global as well : “compareTo()” method is defined as global, thus Comparable interface implementation requires the apex class to be global, this doesn’t makes any sense, why something sortable should be global as well.

  • No easy way to sort on multiple attributes of a class: If we take example of Employee class below,

    global class Employee implements Comparable {
        public String name;
        public Integer age;
        public Date doj;
        public Employee (String n, Integer a, Date d) {
   = n;
            this.age = a;
            this.doj = d;
        // sort by age
        global Integer compareTo(Object other) {
            Integer otherAge = other != null ? ((Employee)other).age : 0;            
            return this.age - otherAge;

    Comparable gives a way to define natural ordering only, so in the above class using Comparable and no other hacks we can just sort on one attribute i.e. age. It would be nice to have support for “Comparator” interface like java as well, so that sorting support can be easily added for other attributes as well, for ex. sort by doj or name. 

    • Side Update : In my next post, I will be covering how to sort on multiple fields using the single comparable interface.



Posted an idea to fill this gaps in next release. Please promote, if you also agree to these gaps.

Related reading

Your thoughts ?

Looking forward for the same.

Leave a Reply

%d bloggers like this: