Salesforce | Sort “wrapper class” objects alphabetically based on a String parameter

| By Webner

Suppose we have a Wrapper class with fName as a string instance variable and we want to sort a list of objects alphabetically based on value of this variable.

1. Implement Comparable interface :

global class MyWrapperclass implements Comparable 
  public String fName {get;set;
public MyWrapperclass(String fullName) 
public MyWrapperclass()        

2. Override the compareTo method as below :

global Integer compareTo(Object objToCompare) {	 
if (objToCompare==NULL)
return 0;	
MyWrapperclass myObj = (MyWrapperclass) objToCompare;
String fn = myObj.fullName;
if (fn==NULL) 
if (this.fullName==NULL)
return 0; 
return this.fullName.compareTo(fn);

3. Sort your list :

 public void sortMyList() 
courseCatalogList = new List();
CourseCatalogWrapper obj1  = new CourseCatalogWrapper();
obj1.fName = ‘John’;
CourseCatalogWrapper obj2  = new CourseCatalogWrapper();
obj2.fName = ‘Aarav’;
CourseCatalogWrapper obj3  = new CourseCatalogWrapper();
obj3.fName = ‘Nick’;

Leave a Reply

Your email address will not be published. Required fields are marked *