Implement Custom Sorting in Apex
List class in Salesforce provided a sort method, however there are certain standard rules that the method uses to sort the list by default
But, what if you had a custorm sorting requirement and you wanted to sort the Opportunities by a custom field.
In the below Example we are going to sort it by opportunity amount.
Implement the Comparable Interface
To accomplish this we have to create a wraper class and implement the comapable interface.
public class OpportunityWrapper implements Comparable {
public Opportunity oppy;
// Constructor
public OpportunityWrapper(Opportunity op) {
// Guard against wrapping a null
if(op == null) {
Exception ex = new NullPointerException();
ex.setMessage('Opportunity argument cannot be null');
throw ex;
}
oppy = op;
}
Implement the Compared to Method
The implementation of the compareTo method in this class compares two opportunities based on the Amount field—the class member variable contained in this instance, and the opportunity object passed into the method.
public Integer compareTo(Object compareTo) {
// Cast argument to OpportunityWrapper
OpportunityWrapper compareToOppy = (OpportunityWrapper)compareTo;
// The return value of 0 indicates that both elements are equal.
Integer returnValue = 0;
if ((oppy.Amount == null) && (compareToOppy.oppy.Amount == null)) {
// both wrappers have null Amounts
returnValue = 0;
} else if ((oppy.Amount == null) && (compareToOppy.oppy.Amount != null)){
// nulls-first implementation
returnValue = -1;
} else if ((oppy.Amount != null) && (compareToOppy.oppy.Amount == null)){
// nulls-first implementation
returnValue = 1;
} else if (oppy.Amount > compareToOppy.oppy.Amount) {
// Set return value to a positive value.
returnValue = 1;
} else if (oppy.Amount < compareToOppy.oppy.Amount) {
// Set return value to a negative value.
returnValue = -1;
}
return returnValue;
}