Newer Version Available
List Sorting
Using the List.sort method, you can sort elements in a list. Sorting is in ascending order for elements of primitive data types, such as strings. The sort order of other more complex data types is described in the chapters covering those data types.
You can sort custom types (your Apex classes) if they implement the Comparable interface. Alternatively, a class implementing the Comparator interface can be passed as a parameter to the List.sort method. For more information on the sort order used for sObjects, see Sorting Lists of sObjects.
This example shows how to sort a list of strings and verifies that the colors are in ascending order in the list.
1List<String> colors = new List<String>{
2 'Yellow',
3 'Red',
4 'Green'};
5colors.sort();
6System.assertEquals('Green', colors.get(0));
7System.assertEquals('Red', colors.get(1));
8System.assertEquals('Yellow', colors.get(2));For the Visualforce SelectOption control, sorting is in ascending order based on the value and label fields. See this next section for the sequence of comparison steps used for SelectOption.
Default Sort Order for SelectOption
- The value field is used for sorting first.
- If two value fields have the same value or are both empty, the label field is used.
The disabled field isn’t used for sorting.
For text fields, the sort algorithm uses the Unicode sort order. Also, empty fields precede non-empty fields in the sort order.
In this example, a list contains three SelectOption elements. Two elements, United States and Mexico, have the same value field (‘A’). The List.sort method sorts these two elements based on the label field, and places Mexico before United States, as shown in the output. The last element in the sorted list is Canada and is sorted on its value field ‘C’, which comes after ‘A’.
1List<SelectOption> options = new List<SelectOption>();
2options.add(new SelectOption('A','United States'));
3options.add(new SelectOption('C','Canada'));
4options.add(new SelectOption('A','Mexico'));
5System.debug('Before sorting: ' + options);
6options.sort();
7System.debug('After sorting: ' + options);The output of the debug statements shows the contents of the list, both before and after the sort.
1DEBUG|Before sorting: (System.SelectOption[value="A", label="United States", disabled="false"],
2 System.SelectOption[value="C", label="Canada", disabled="false"],
3 System.SelectOption[value="A", label="Mexico", disabled="false"])
4DEBUG|After sorting: (System.SelectOption[value="A", label="Mexico", disabled="false"],
5 System.SelectOption[value="A", label="United States", disabled="false"],
6 System.SelectOption[value="C", label="Canada", disabled="false"])