Custom Sorting for Wrapper Classes using Apex

Hello, so you want to Sort List<-Wrapper> other than standard sObjects, i.e., you need to sort a wrapper class.

In order to acheive sorting, we need to Implement standard class Comparable , Here we will sort using inputA in class

Consider a wrapper class as follows,

global class wrapper implements Comparable{

	public string inputA;
    public string inputB;
    public string inputC;
    
    public wrapper(string inputA, string inputB, string inputC){
    	this.inputA = inputA;
        this.inputB = inputB;
        this.inputC = inputC;
    }
    
    /* so here is the 'Trick', now add following method in your class */
    
    public Integer compareTo(Object compareTo) {
        wrapper compareItem = (wrapper)compareTo;
        if (inputA == compareItem.inputA) return 0;
        if (inputA > compareItem.inputA) return 1;
        return -1;        
    }
}

So if you want to sort using inputB/C use inputB/C instead of inputA

Example Explained

So I'm initialising above class and adding Items,

List<wrapper> wList = new List<wrapper>();
wList.add(new wrapper('two', 'foo2', 'bar2'));
wList.add(new wrapper('three', 'foo3', 'bar3'));
wList.add(new wrapper('one', 'foo1', 'bar1'));

/*Now i'm sorting above list. It will sort in oreder of one, two, three because we used inputA in compareMethod, so it will sort using first parameter in class*/

wList.sort();
system.debug(wList);

output

Subscribe to Phanindra Mangipudi

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe