pozil / apex-sorting

Sample Code for Sorting in Apex

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Warning Starting from Winter '24, use the new Comparator interface instead of this.

Sample Code for Sorting in Apex

This repository contains sample code for advanced sorting with Apex. It presents two approaches that go beyond the default List.sort method.

Sorting Lists of sObjects with Custom Ordering

SortableAccount demonstrates how you can sort a list of Account records based on the ShippingCountry field:

SortableAccount.sort(List<Account>);

Sorting Lists with Reusable Comparators

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.

About

Sample Code for Sorting in Apex


Languages

Language:Apex 100.0%