I already know about the equivalent of Comparable
– the class to be sorted should implement Comparable
and then you can sort a List of said class.
But, how about Comparator
?
In java, the Collections.sort()
method can take a Comparator
, so that the sorting and the class implementation are separated. This enables a class to be sorted in different ways.
If I want more than one way of sorting a class, how can this be done in Apex? I have found nothing similar. I've tried extending the class and over-riding the compareTo()
method, but that introduced many problems. Is there a better way?
Best Answer
While Comparator isn't available out of the box, it's not terribly hard to implement. However, your performance will be considerably worse than a native solution, so you'll need to test and see how many rows you can actually sort before it becomes intolerable.
From here, you can create your own solutions:
Which would let you sort as you like:
This should work with any sort of data type, even custom classes, as long as you can implement the "compare" method. This version also doesn't take into consideration null values specifically, so you may need to adjust your implementations accordingly.