Sorting the list rows via apex Comparable interface

For sorting the existing data we can use ORDER BY clause in SOQL query, however for non existing data we usually create 'map' then take help from 'for' loop compare from previous values which involves lots of code consequently may bump up the apex cpu time.

So to avoid this we can use Comparable interface, where we can pass the list of existing or non existing data in org, for better understanding please refer the below code, you can try in your org as well :


1. Create a global class which implement the comparable interface :
--------------------------------------------------------------
global class SortingUser implements Comparable {
    public Long id;
    public String name;
    public String phone;
    
    // Constructor
    public SortingUser(Long i, String n, String p) {
        id = i;
        name = n;
        phone = p;
    }
    
    // Implement the compareTo() method, mendatory method it returns an Integer value that is the result of the comparison
    global Integer compareTo(Object compareTo) {
        SortingUser compareToUser = (SortingUser)compareTo;

        // Used 'id' variable/column to make it sort according to id
        if (id == compareToUser.id) return 0; 
        if (id > compareToUser.id) return 1;
        return -1;        
    }
}
--------------------------------------------------------------


2. Create a mock class from where you can push unsorted data:
--------------------------------------------------------------
public class SortingMock{
    
    
    list<wrapperList_class> wrc = new list<wrapperList_class>(); //List of wrrapper class 
    
    //Using constructor to set the value
    public SortingMock(){
    
        // pushing unsorted rows in the list
        wrc.add(new wrapperList_class(009,'Sam sessford', '+1 984 651 3214' ));
        wrc.add(new wrapperList_class(012,'John Cheong', '+1 657 249 8741' ));
        wrc.add(new wrapperList_class(010,'Alex Mahom', '+1 321 245 6541' ));
        wrc.add(new wrapperList_class(007,'Honey Verma', '+1 985 541 4651' ));
        wrc.add(new wrapperList_class(011,'Desmond cina', '+1 523 456 7651')); 
    }
    
    
    public void doSorting()
    {
        system.debug('Unsorted : '+ wrc);
        list<SortingUser > lstSu = new list<SortingUser >();
        for(wrapperList_class wc: wrc)
        {
            //pushing the values/rows which we want to sort
            lstSu.add(new SortingUser(wc.wrpId, wc.wrpName, wc.wrpPhone));
        }
        lstSu.sort(); // sort(), main method which will sort the rows/values
        system.debug('Sorted : '+ lstSu);
    }
    
    // wrapper class for mock list
    public class wrapperList_class
    {
        public long wrpId;
        public string wrpName;
        public string wrpPhone;
        
        public wrapperList_class(long id, string name, string phone)
        {
            wrpId = id;
            wrpName = name;
            wrpPhone = phone;
        }
    }

}

--------------------------------------------------------------


3. Run below code snippet in anonymous block (set the debug logs first to validate the result):
--------------------------------------------------------------
SortingMock sm = new SortingMock();

sm.doSorting();
--------------------------------------------------------------


4. Check the debug logs :
--------------------------------------------------------------
37.0 APEX_CODE,FINEST;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;....
Execute Anonymous:     SortingMock sm = new SortingMock();
Execute Anonymous: sm.doSorting();
......
23:33:00.2 (34468397)|USER_DEBUG|[20]|DEBUG|Unsorted : (
wrapperList_class:[wrpId=9, wrpName=Sam sessford, wrpPhone=+1 984 651 3214], 
wrapperList_class:[wrpId=12, wrpName=John Cheong, wrpPhone=+1 657 249 8741], 
wrapperList_class:[wrpId=10, wrpName=Alex Mahom, wrpPhone=+1 321 245 6541], 
wrapperList_class:[wrpId=7, wrpName=Honey Verma, wrpPhone=+1 985 541 4651], 
wrapperList_class:[wrpId=11, wrpName=Desmond cina, wrpPhone=+1 523 456 7651])
......
23:33:00.2 (56090447)|USER_DEBUG|[27]|DEBUG|Sorted : (
SortingUser:[id=7, name=Honey Verma, phone=+1 985 541 4651], 
SortingUser:[id=9, name=Sam sessford, phone=+1 984 651 3214], 
SortingUser:[id=10, name=Alex Mahom, phone=+1 321 245 6541], 
SortingUser:[id=11, name=Desmond cina, phone=+1 523 456 7651], 

SortingUser:[id=12, name=John Cheong, phone=+1 657 249 8741])
......
--------------------------------------------------------------

Here you can see Unsorted debug logs where ids were unordered (9, 12, 10, 7 and 11) and then lstSu.sort(); snippet changed the order and gave ordered list as you can see it in Sorted debug where ids are in proper order (7, 9, 10, 11 and 12)




Comments

  1. Sorting list rows via Apex Comparable enhances data organization and retrieval. Leveraging this feature streamlines data manipulation, making it easier to locate specific information. 75Mbps Good Gaming This efficient method contributes to improved application performance.

    ReplyDelete
  2. I am grateful for this blog to distribute knowledge about this significant topic. Here I found different segments and now I am going to use these new instructions with new enthusiasm. You can also check the best Salesforce Development Company in USA and Australia.

    ReplyDelete

Post a Comment

Popular posts from this blog

Understanding the common UNABLE TO LOCK ROW issue with bulk data job

Create Salesforce bulk API job with Workbench