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.
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(); }