Tuesday, January 25, 2011

Custom Sorting of List collections in Salesforce (Apex code)


Custom Sorting of List collections in Salesforce (Apex code)  :-
Here I would like to share apex code that sort List of SObject and list of object.  It was started when I got “To many script statements” error when sort collections by using Sorting algorithm.
While it may be easy to fall back to a custom sorting algorithm a combination of the standard List.sort() method and associative arrays (Maps) can provide a significantly reduced statement footprint. Here is Apex code for sorting Sobject List.

 public class AP_SortHelper {  
  
 public static void sortList(List<Sobject> items, String sortField, String order){


       List<Sobject> resultList = new List<Sobject>();
  
        //Create a map that can be used for sorting
       Map<object, List<Sobject>> objectMap = new Map<object, List<Sobject>>();
          
       for(Sobject ob : items){
                if(objectMap.get(ob.get(sortField)) == null){  // For non Sobject use obj.ProperyName
                    objectMap.put(ob.get(sortField), new List<Sobject>());
                }
                objectMap.get(ob.get(sortField)).add(ob);
        }      
        //Sort the keys
        List<object> keys = new List<object>(objectMap.keySet());
        keys.sort();
      
        for(object key : keys){
            resultList.addAll(objectMap.get(key));
        }
      
        //Apply the sorted values to the source list
        items.clear();
        if(order.toLowerCase() == 'asc'){
            for(Sobject ob : resultList){
                items.add(ob);
            }
        }else if(order.toLowerCase() == 'desc'){
            for(integer i = resultList.size()-1; i >= 0; i--){
                items.add(resultList[i]); 
            }
        }
    }
  
    static testMethod void myUnitTest(){
        List<Account> accList = [select Name,AccountNumber from Account limit 100];
        sortList(accList,'Name', 'ASC');
         String lastValue = null;
        String currentValue = null;       
        for (Account acc : accList) {
               currentValue = acc.Name;
               System.assertEquals(currentValue.compareTo(lastValue)>=0, true);
        }
        lastValue = currentValue;
     }
}

6 comments:

  1. Nice work. I modified for SelectOptions...works perfect. Thanks.

    ReplyDelete
  2. good Job man.. This is pretty neat. Thanks for sharing.

    ReplyDelete
  3. Agreed - an elegant bit of coding, and I think the best algorithm for the job under Apex.

    ReplyDelete
  4. Great solution for sObject,

    Please add implementation for list on field x

    ReplyDelete
  5. does not work for wrapper class

    ReplyDelete

Getting Started with Salesforce DX

Salesforce DX is a great way to let multiple peoples work together and also make deployment much easier. Salesforce DX make release cycle m...