Collator Class
Contains methods to get locale-specific instances that can be used for comparisons
and sorting. Use the getInstance() method to obtain the
Collator instance for a given locale and pass the Collator as the Comparator parameter to
the list.sort() method.
Namespace
Usage
Because locale-sensitive sorting can produce different results depending on the user running the code, avoid using it in triggers or in code that expects a particular sort order.
Example
This example performs a default list sort and then uses Collator to sort based on the user locale.
1@IsTest
2 static void userLocaleSort() {
3
4 string userLocale = 'fr_FR';
5
6 User u = new User(Alias = 'standt', Email='standarduser@testorg.com',
7 EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
8 LocaleSidKey=userLocale, TimeZoneSidKey='America/Los_Angeles',
9 ProfileId = [SELECT Id FROM Profile WHERE Name='Standard User'].Id,
10 UserName='standarduser' + DateTime.now().getTime() + '@testorg.com');
11
12 System.runAs(u) {
13
14 List<String> shoppingList = new List<String> {
15 'épaule désosé Agneau',
16 'Juice',
17 'à la mélasse Galette 5 kg',
18 'Bread',
19 'Grocery'
20 };
21
22 // Default sort
23 shoppingList.sort();
24 Assert.areEqual('Bread', shoppingList[0]);
25
26 // Sort based on user Locale
27 Collator myCollator = Collator.getInstance();
28 shoppingList.sort(myCollator);
29 Assert.areEqual('à la mélasse Galette 5 kg', shoppingList[0]);
30 Assert.areEqual('Bread', shoppingList[1]);
31 Assert.areEqual('épaule désosé Agneau', shoppingList[2]);
32 Assert.areEqual('Grocery', shoppingList[3]);
33 Assert.areEqual('Juice', shoppingList[4]);
34 }
35 }Collator Methods
The following are methods for Collator.
getInstance()
Gets the Collator instance for the current user’s locale.
Signature
public static System.Collator getInstance()
Return Value
Type: Collator Class