Sub topic 14
Sorting Lists and the Comparable Interface
This chapter assumes you can write basic Apex, use List methods such as add and get, and read a class definition. It covers how List.sort() orders elements and how to define your own order for custom classes.
How List.sort() orders primitives
List.sort() sorts a list in place. It returns nothing, so don't assign its result to a variable. The default order is ascending.
List<Integer> scores = new List<Integer>{42, 7, 19};
scores.sort();
System.debug(scores); // (7, 19, 42)
List<String> names = new List<String>{'Grace', 'Ada', 'Linus'};
names.sort();
System.debug(names); // (Ada, Grace, Linus)Lists of Integer, Decimal, Date, Datetime, Id, and String all have a built-in order. String sorting is case-sensitive, so uppercase letters sort before lowercase ones. Set and Map have no sort() method. To sort their contents, copy them into a list first, for example new List<String>(tags).
Sorting SObjects
A list of SObjects also sorts without extra code, but the order is fixed by the platform. Records are compared field by field, starting with standard fields such as Id and Name. This is rarely the order you want. For a specific order, use ORDER BY in the SOQL query, or sort a list of wrapper objects as shown below.
Defining your own order with Comparable
A class that implements the Comparable interface tells sort() how to compare two of its instances. The interface has one method, compareTo(Object other). It returns an Integer:
| Return value | Meaning |
|---|---|
| Negative | This instance sorts before `other` |
| Zero | The two are equal for sorting purposes |
| Positive | This instance sorts after `other` |
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;
if (salary == o.salary) {
return 0;
}
return salary > o.salary ? 1 : -1;
}
}
List<Employee> staff = new List<Employee>{
new Employee('Ada', 120),
new Employee('Grace', 100)
};
staff.sort(); // Grace first, then AdacompareTo takes an Object, so you must cast it to your class. When sort() runs, it calls compareTo on the elements and arranges them by the returned values.
Common errors
- Casting without a type check. If the list can hold other types,
(Employee) otherthrows aSystem.TypeException. In a list typed asList<Employee>, this is safe. - Ignoring null fields. Comparing a
nullsalary with>does not behave as a normal comparison. Handlenullexplicitly incompareTo, for example by treating it as the smallest value. - Expecting descending order. To sort in descending order, reverse the comparison inside
compareTo, for example by returning-1where the code above returns1. You can also callstaff.sort()and then reverse the list manually. - Inconsistent results. If
a.compareTo(b)is positive,b.compareTo(a)should be negative. Breaking this rule produces unpredictable ordering.
Exercise
A Task class implements Comparable and sorts by a Integer priority field in ascending order. What change to compareTo makes sort() put the highest priority number first?
Show answer
Reverse the comparison. Return a positive number when this priority is lower than the other, and a negative number when it is higher. For example, return other.priority - priority; gives descending order, because a larger other.priority makes the result positive and moves this instance later.
Exercise
Why can't you call sort() directly on a Set<String>, and how do you get a sorted result?
Show answer
Set has no sort() method because sets are unordered. Copy the set into a list with new List<String>(mySet), then call sort() on that list.