Product SiteDocumentation Site

5.3.18.2. Sorting with more than one order

The String class compareTo method only implements a sort ordering for an ascending sort using a strict comparison. Frequently it is desirable to override a class-defined sort order or even to sort items that do not implement a compareTo method. To change the sorting criteria, use the sortWith method. The sortWith method takes a single argument, which is a Comparator object that implements a compare method. The compare method performs comparisons between pairs of items. Different comparators can be customized for different comparison purposes. For example, the Rexx language provides a DescendingComparator class that will sort items into descending order:

Example 5.178. Multi-order sorting

::CLASS 'DescendingComparator' MIXINCLASS Comparator
::METHOD compare
use strict arg left, right
return -left~compareTo(right)

The DescendingComparator merely inverts the result returned by the item compareTo method. Our previous example

Example 5.179. Descending compare sorting

myArray = .array~of("Zoe", "Fred", "Xavier", "Andy")
myArray~sortWith(.DescendingComparator~new)

do name over myArray
   say name
end

now displays in the order "Zoe", "Xavier", "Fred", "Andy".
Custom Comparators are simple to create for any sorting purpose. The only requirement is implementing a compare method that knows how to compare pairs of items in some particular manner. For example, to sort our Employee class by name instead of the default employee id, we can use the following simple comparator class:

Example 5.180. Custom compare sorting

::CLASS EmployeeNameSorter MIXINCLASS Comparator
::METHOD compare
  use strict arg left, right
  return left~name~compareTo(right~name)  -- do the comparison using the names