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

Author - Neha Mishra

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) 
{    
fName=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) 
fn='';
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’;
courseCatalogList.add(obj1);
courseCatalogList.add(obj2);
courseCatalogList.add(obj3);
courseCatalogList.sort();
}

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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