Custom Sorting In Apex
Yadhu Krishnan
Senior Salesforce Developer at Inno Valley Works | 5x Certified | Empowering Businesses with Salesforce Magic!
We may have encountered this scenario where we wished it would be great if we could sort a few records in a custom order that we needed for a specific functionality. For instance, let's assume we have a few accounts and we have a condition where the Accounts should be sorted based on AnnualRevenue but the accounts with less rating should come at the end and you want this logic to be applied on multiple apex codes. Wouldn't you be happy if you could achieve this in two lines?
listOfAccounts.sort(sortByRevenue);
listOfAccounts.sort(sortByRating);
We can now achieve this in apex using the 'Comparator' interface. We can achieve different sort orders with the Comparator interface’s compare() method, and by passing the Comparator as a parameter to List.sort(). Note that we must explicitly handle null inputs in the compare() method.
The compare() method compares the two arguments and returns a negative integer, zero, or a positive integer depending on whether the first argument is less than, equal to, or greater than the second argument.
Let's check the implementation for the scenario we discussed above.
Implementation:
领英推荐
AccountSortByRating.cls
public class AccountSortByRating implements Comparator < Account > {
public Integer compare(Account e1, Account e2) {
System.debug(e1 + '' + e2);
Integer result;
if (e1?.Rating == null && e2?.Rating == null) {
result = 0;
} else if (e1?.Rating == null) {
result = -1;
} else if (e2?.Rating == null) {
result = 1;
} else if (e1.Rating == e2.Rating) {
result = 0;
} else if (e1.Rating < e2.Rating) {
result = 1;
} else if (e1.Rating > e2.Rating) {
result = -1;
} else {
result = 0;
}
return result;
}
}
SortByAnnualRevenue.cls
public class SortByAnnualRevenue implements Comparator < Account > {
public Integer compare(Account e1, Account e2) {
System.debug(e1 + '' + e2);
Integer result;
if (e1?.AnnualRevenue == null && e2?.AnnualRevenue == null) {
result = 0;
} else if (e1?.AnnualRevenue == null) {
result = -1;
} else if (e2?.AnnualRevenue == null) {
result = 1;
} else if (e1.AnnualRevenue == e2.AnnualRevenue) {
result = 0;
} else if ((e1.AnnualRevenue < e2.AnnualRevenue)) {
result = -1;
} else if (e1.AnnualRevenue > e2.AnnualRevenue) {
result = 1;
} else {
result = 0;
}
return result;
}
}
Now let's try in Anonymous window:
List<Account> newList = [SELECT Id,Name,AnnualRevenue, Rating FROM Account LIMIT 10];
System.debug(newList);
AccountSortByRating sortByRating = new AccountSortByRating();
newList.sort(sortByRating);
SortByAnnualRevenue sortByAnnualRevenue = new SortByAnnualRevenue();
newList.sort(sortByAnnualRevenue);
for(Account acc:newList){
System.debug(acc);
}
Result: