Wednesday, March 28, 2012

Sort an Apex class Object List

[Edit : Now there is an interface natively provided by salesforce to sort the class object lists]

I recently needed to sort an apex class object List which was retrieved through a webservice callout as it could not be sorted at the service end.

This is the apex method which was used to build it

 public void testsort(){
        map<string,List<accClass>> stracc = new map<string,list<accClass>>();
        for(accClass a:accClassobj ){
            if(stracc.containsKey(a.name))
                stracc.get(a.name).add(a);           
            else
              stracc.put(a.name,new accclass[]{a});          
        }
        accclassobj= new list<accclass>();
        list<string> nameList = new list<string>();
        nameList.addAll(stracc.keyset());
        nameList.sort();       
        for(string s:nameList){
           accclassobj.addAll(stracc.get(s));          
        }

Steps involved in sorting

1. build a map with object parameter as the key by which we gonna sort and List<object> as the value.
2. sort the keyset
3. arrange the values based on the sorted keyset, so that object gets sorted by that parameter

It is a map of parameter and list of object but not parameter and just object to handle the records which will have same parameters. This sorting handles null values automatically. This sorting can never be dynamic and you will need to create more methods based on the object parameter by which sorting is needed.