How to Use Apex Collator Class for Locale-Sensitive Sorting in Salesforce

Salesforce Winter'24 release came with Collator class, that is meant to provide locale sensitive sorting.

Locale-sensitive sorting refers to the process of sorting strings or other data types based on the rules and conventions of a specific locale. A locale is a set of parameters that defines the user's language, region, and any special variant preferences that the user wants to see in their user interface. Different locales have different rules for how strings are sorted and compared.

For example, in English, the sorting order is generally straightforward and follows the ASCII values of characters. However, in languages like German, characters like "ä", "ö", and "ü" have special sorting rules. Similarly, in some Asian languages, the sorting order can be quite complex.

Java provides the Collator class in the java.text package for locale-sensitive sorting. You can create an instance of Collator for a specific locale and then use it to compare strings in a way that is appropriate for that locale. Similar Collator class is now available in Salesforce with Winter'24 release.

Hands-on Demo

This short < 6 mins video gives a demo of the Collator class and explains how, and when it should be used, along with tips on where it shouldn't be used.

Code Snippet

You can run this code snippet in your Winter’24 Sandbox or pre-release org, needs API version 59.0 and beyond.

Previous
Previous

How to Make Trailhead Reading Experience Easier on the Eyes

Next
Next

Salesforce Functions Retirement (History 2019-2023)