Came across a scenario where I had to sort a wrapper class. Normal list sorting is simple, list.sort(); would help. But for a wrapper class, it’s not straight-forward but it isn’t that hard. Below is a simple wrapper class without sorting – this wrapper has 2 columns : Area and AD.
global class AreaWrapper{
public String AreaName{get;set;}
public String ADName{get;set;}
public AreaWrapper(){
AreaName = '';
ADName = '';
}
}
To make it sort by ADName, we need the class to use “implements Comparable” and “CompareTo”.
global class AreaWrapper implements Comparable{
public String AreaName{get;set;}
public String ADName{get;set;}
public AreaWrapper(){
AreaName = '';
ADName = '';
}
global Integer compareTo(Object objToCompare) {
//Sort by AreaName Alphabetically
return AreaName.compareTo(((AreaWrapper)objToCompare).AreaName);
}
}
If you want to add another sort (within AreaName sorting) i.e., if you want to sort by AreaName and then by ADName, this works.
global Integer compareTo(Object objToCompare) {
AreaWrapper that = (AreaWrapper) objToCompare;
Integer c = this.AreaName.compareTo(that.AreaName);
if (c != 0) {
return c;
} else {
return this.ADName.compareTo(that.ADName);
}
}
And do not forget to sort the wrapper list before displaying in visualforce page.
public List AreaWrapper myWrapperList{
get{
myWrapperList.sort();
return myWrapperList;
}
private set;
}
One Reply to “Wrapper Class Multiple Value Sorting”