Hello friends, In this post we are going to learn about apex warpper class list sorting that helps you to sort data either integer/decimal or string inside wrapper class. So let's get started,

Sort data inside wrapper class in apex 

In apex, to sort primitive datatype there is a builtin function that we can implement by using comparable interface. This interface introduced by the salesforce in summer'12 so let's understand this interface with a code example.

First of all we have to create an apex class using comparable interface. 

Sample Code:

 public class SortWapperListHandler implements Comparable{
public String DonarName{get;set;}
public Decimal DonationAmount{get;set;}

public enum SORT_BY {ByName,ByAmount}

//Variable that hold default sorting, ByName
public static SORT_BY sortBy = SORT_BY.ByName;

public SortWapperListHandler(String DonarName,Decimal DonationAmount){
this.DonarName = DonarName;
this.DonationAmount = DonationAmount;
}

public Integer compareTo(Object objToCompare){
//Sort Donar Name Alphabetically
if(sortBy == SORT_BY.ByName){
return DonarName.compareTo(((SortWapperListHandler)objToCompare).DonarName);
}
else{
//Sort by Donation Amount
return Integer.valueOf(DonationAmount - ((SortWapperListHandler)objToCompare).DonationAmount);
}
}
}

compareTo() method:
The compareTo() method return following integer value.

  1. 0 if both object is equal.
  2. >0 if the instance object is greater than "objToCompare".
  3. <0 if the instance object is smaller than "objToCompare".

As you can see in above code, we are sorting on the basis of either DonarName or DonationAmount. The logic can be anything depending on your business requirement.

To test this code we have to run the below code in developer console.

 List<SortWapperListHandler> donations = new List<SortWapperListHandler>{
new SortWapperListHandler('John',6341.30),
new SortWapperListHandler('Anna',7596.55)
};

SortWapperListHandler.sortBy = SortWapperListHandler.SORT_BY.ByName;
donations.sort();
System.debug('Sort by donar name^^^'+donations);

SortWapperListHandler.sortBy = SortWapperListHandler.SORT_BY.ByAmount;
donations.sort();
System.debug('Sort by donation amount^^^'+donations);

Output:


Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.