Sub topic 14
Sorting Lists and the Comparable Interface
This chapter assumes you can create a List, call its basic methods, and loop over it. It also assumes you can read a simple SOQL query. Sorting is a List-only operation in Apex, so the chapter covers three things: what List.sort() does on its own, how to teach it a custom order with Comparable, and how to choose between sorting in Apex and sorting in SOQL.
What sort() does by default
List.sort() reorders the list in place. It returns nothing, so don't assign its result to a variable. For primitives the order is ascending.
List<Integer> scores = new List<Integer>{5, 1, 3};
scores.sort();
System.debug(scores); // (1, 3, 5)
List<String> words = new List<String>{'cherry', 'apple', 'Banana'};
words.sort();
System.debug(words); // (Banana, apple, cherry)Strings compare by Unicode value, so every uppercase letter sorts before every lowercase letter. 'Banana' comes first because 'B' is code point 66 and 'a' is 97. If users see the result, you probably need a case-insensitive order, which is covered below.
sort() has no descending flag. Sort ascending, then call reverse():
List<Integer> scores = new List<Integer>{5, 1, 3};
scores.sort();
scores.reverse();
System.debug(scores); // (5, 3, 1)Null elements sort before non-null values in an ascending sort of primitives. If your data can contain nulls, check the position of the nulls in a quick test rather than assuming.
Sets and Maps have no sort
A Set has no defined order, and a Map does not let you sort its entries. To get sorted output, copy the elements into a List and sort that.
Set<String> tags = new Set<String>{'soql', 'apex', 'trigger'};
List<String> sortedTags = new List<String>(tags);
sortedTags.sort();
System.debug(sortedTags); // (apex, soql, trigger)
Map<String, Integer> counts = new Map<String, Integer>{'b' => 2, 'a' => 5, 'c' => 1};
List<String> keys = new List<String>(counts.keySet());
keys.sort();
for (String key : keys) {
System.debug(key + ' = ' + counts.get(key)); // a = 5, b = 2, c = 1
}The Map stays unchanged. You sort a separate list of its keys and use that list to drive the loop. To order entries by value, you need a list of wrapper objects, which the next section covers.
Custom order with Comparable
When a list holds instances of your own class, sort() has no way to know which instance comes first. You supply the rule by implementing the built-in Comparable interface. It has one method:
Integer compareTo(Object other)The return value follows a fixed contract, where this is the instance the method runs on:
| Return value | Meaning |
|---|---|
| Negative integer | `this` sorts before `other` |
| 0 | The two are equal for sorting purposes |
| Positive integer | `this` sorts after `other` |
The class below sorts employees by salary, breaks ties by name, and treats a null salary as the lowest value.
public class Employee implements Comparable {
public String name;
public Decimal salary;
public Employee(String name, Decimal salary) {
this.name = name;
this.salary = salary;
}
public Integer compareTo(Object other) {
Employee o = (Employee) other;
Integer bySalary = compareSalary(salary, o.salary);
if (bySalary != 0) {
return bySalary;
}
return name.compareTo(o.name);
}
private static Integer compareSalary(Decimal a, Decimal b) {
if (a == b) {
return 0;
}
if (a == null) {
return -1;
}
if (b == null) {
return 1;
}
return a < b ? -1 : 1;
}
}Run this in Anonymous Apex once the class is saved:
List<Employee> staff = new List<Employee>{
new Employee('Grace', 100),
new Employee('Ada', 120),
new Employee('Alan', 100),
new Employee('Linus', null)
};
staff.sort();
for (Employee e : staff) {
System.debug(e.name + ' ' + e.salary);
}
// Linus null, Alan 100, Grace 100, Ada 120Linus comes first because null counts as lowest. Alan and Grace have equal salaries, so String.compareTo orders them by name. Printing the list directly would show object references instead of names, which is why the loop prints fields.
Rules for a correct compareTo
- Cast
otherto your class first. The parameter type isObject, so a list that contains a different type causes aTypeExceptionat runtime. - Keep the ordering consistent. If
a.compareTo(b)is negative, thenb.compareTo(a)must be positive. A rule that breaks this produces results that look random. - Compare only fields the sort should depend on. Fields that change between calls make the order unpredictable.
- Decide how nulls behave and write that decision into the method, as
compareSalarydoes. An unguardedsalary > o.salarywith a null on one side does not give a usable order. - Do the cheap checks first.
sort()callscompareTomany times, so heavy work inside it adds to your CPU time limit.
Sorting by a Comparator
Newer API versions also provide a Comparator<T> interface. It separates the sort rule from the data class, so you can have several orders for the same type, or sort a class you cannot modify. It has one method, compare(T a, T b), and uses the same negative, zero, positive contract. You pass the comparator to sort().
public class EmployeeNameInsensitive implements Comparator<Employee> {
public Integer compare(Employee a, Employee b) {
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
}
}List<Employee> staff = new List<Employee>{
new Employee('grace', 100),
new Employee('Ada', 120),
new Employee('alan', 90)
};
staff.sort(new EmployeeNameInsensitive());
// Ada, alan, graceLowercasing both names makes the order case-insensitive, which the default string sort is not. If your org's API version predates Comparator, use Comparable instead.
Sorting SObjects
List.sort() also works on a list of SObjects, but the order comes from a fixed internal sequence of fields that you do not control. For anything other than a quick check, do not rely on it. You have two better options.
- Sort in the query with
ORDER BY, for exampleSELECT Id, Name, Amount FROM Opportunity ORDER BY Amount DESC. - Wrap each record in a small class that implements
Comparableand holds the field you want to sort on.
The second option is needed when the sort key is computed in Apex, such as a total from child records, because SOQL cannot order by it.
public class OpportunityWrapper implements Comparable {
public Opportunity record;
public OpportunityWrapper(Opportunity record) {
this.record = record;
}
public Integer compareTo(Object other) {
OpportunityWrapper o = (OpportunityWrapper) other;
Decimal a = record.Amount == null ? 0 : record.Amount;
Decimal b = o.record.Amount == null ? 0 : o.record.Amount;
if (a == b) {
return 0;
}
return a > b ? -1 : 1; // larger amounts first
}
}Returning -1 when the amount is larger puts the biggest opportunities first, so no reverse() call is needed.
Choosing where to sort
The diagram shows the decision. The key question is whether the order can be expressed as fields on one queried object.
ORDER BY is usually the best choice for query results. The database does the work, it costs no Apex CPU time, and it needs no extra class. Reach for Comparable when the order depends on logic that only Apex can compute.
Common mistakes
- Expecting a return value.
List<Integer> sorted = scores.sort();does not compile, becausesort()returns nothing. Callsort()on the list and then use the list. - Sorting inside a loop. Sort once after you finish adding elements. Sorting on every iteration repeats the same work and burns CPU time.
- Forgetting
implements Comparable. A custom class without the interface cannot be ordered, andsort()fails at runtime. - Treating equal as unordered. When
compareToreturns 0, the relative order of those two elements is not something to depend on. Add a tiebreaker field, asEmployeedoes with name, whenever the output must be repeatable. - Sorting a Set's backing data. A
Setcannot be sorted in place. Convert it to a List first.
Exercise
A list of Opportunity records must be shown with the largest Amount first. One version of the requirement says the amount is a field on the record. Another says the ranking is the Amount plus the sum of related line item totals, computed in Apex. Which sorting approach fits each version, and why?
Show answer
For the first version, use ORDER BY Amount DESC in the SOQL query. The database sorts on a stored field, so no Apex code or CPU time is needed. For the second version, SOQL cannot order by a value computed in Apex, so wrap each Opportunity in a class that implements Comparable (or write a Comparator). The class stores the computed ranking and compareTo orders by it, returning a negative value when this ranking is larger so the biggest comes first. Then call sort() on the list of wrappers.
Exercise
You have a Map<String, Integer> of word counts and want to print the words in alphabetical order. The Map has no sort method. What do you do, and does the Map itself change?
Show answer
Copy the keys into a list with new List<String>(counts.keySet()), call sort() on that list, and loop over the sorted list, reading each count with counts.get(key). The Map does not change. Only the separate list of keys is reordered.