Sorting lists or other comparable collections
Call the sort method on the list to sort a list in place.
myList.sort()For descending order, use the sortDescending method.
By default, these methods do not use a localized sort collation order. For localized sorting, pass a comparator as a method argument.
Use gw.api.util.LocaleUtil to
get the comparator for the current locale. For example:
myList.sort(LocaleUtil.getComparator())If you
need a comparator for a different locale, LocaleUtil provides methods to
get a comparator by language or locale.
To retain the existing list and create a new list rather than sorting in place, use the orderBy and
orderByDescending methods.
Sorting by a value other than the list element
The sortBy
method on a list supports sorting on an element that you derive from
the list element. For example, suppose you had an array list of String values that you want to
sort by the text length. Create a block that takes a String and returns the sort key,
which in this case is the number of characters of the parameter.
The sortBy method sorts the original list in place, and also returns a new list that contains the sorted values. To retain the existing list and return a new list, use the orderBy method.
The following example sorts strings by their length:
var myStrings = {"a", "abcd", "ab", "abc"}
var resortedStrings = myStrings.sortBy( \ str -> str.length )
The following line prints the contents of the collection of sorted strings:
resortedStrings.each( \ str -> print( str ) )This line produces the output:
a
ab
abc
abcd
Similarly, you can use the sortByDescending method, which sorts in the opposite order.
For both of these methods, the block must
return a comparable value. Comparable values include Integer, String, or any other values that
can be compared with the greater than (>)
or less than (<) operators.
By default, these methods do not use a localized sort collation order. For localized sorting, pass a comparator as a second argument to the method.
Advanced sort comparison
In some cases, comparison among your list objects is less straightforward. You might require more complex Gosu code to compare two items in the list. In such cases, use the sort method signature that takes a block that compares two list items.
The block must take two list elements and return true if the first element comes before the second,
or otherwise return false. Using this method signature, the earlier sorting example looks like
the following code:
var strs = new ArrayList<String>(){"a", "abc", "ab"}
var sortedStrs = strs.sort( \ str1, str2 -> str1.length < str2.length )
Although using the sort
method is powerful, in most cases Gosu code is more readable if you use
the sortBy or sortByDescending methods.
By default, these methods do not use a localized sort collation order. For localized sorting, pass a comparator as a second argument to the method.
