Warning Starting from Winter '24, use the new Comparator interface instead of this.
This repository contains sample code for advanced sorting with Apex. It presents two approaches that go beyond the default List.sort method.
SortableAccount demonstrates how you can sort a list of Account records based on the ShippingCountry
field:
SortableAccount.sort(List<Account>);
ListUtils and the Comparator interface demonstrate how you can sort lists with custom reusable comparators such as:
// Sort a list of accounts alphabetically based on shipping country
ListUtils.sort(accounts, new SObjectStringFieldComparator('ShippingCountry'));
// Sort a list of accounts alphabetically based on industry
ListUtils.sort(accounts, new SObjectStringFieldComparator('Industry'));
// Sort a list of accounts based on rating values
// as defined in the rating picklist order (non-alphabetical sort)
ListUtils.sort(accounts, new AccountRatingComparator());
A note on performance: ListUtils
uses a bubble sort algorithm. This works fine in most cases but other algorithms may be more efficient depending on the type and volume of data that you are sorting.