Eclipse Collections Now Supports Indirect Sorting of Primitive Lists
Sometimes the best way to get results is to be indirect
I have recently implemented indirect sort functionality on primitive list types, which are some of many collection types supported by the Eclipse Collections project.
There was a sort functionality on the primitive collections before, the sortThis()
method, which is a wrapper around the Java JDK Arrays.sort
method. The limitation, which was carried over into the primitive list implementation, is that it could only sort an array by its elements and by the elements’ natural order, rather than by a function of its elements and/or some custom comparator.
Why would you want to sort by anything other than by the natural order of value of the element? Here are some possible reasons:
- Reverse sorting
- Sorting by absolute value
- Building an index into an ordered data structure that is impossible or impractical to reorder (e.g., a tabular data set implemented as in in-memory columnar store)
This also supports the functionality described in an old open feature request for the JDK (see “(coll) Arrays.sort cannot sort primitive arrays with a comparator” https://bugs.openjdk.java.net/browse/JDK-4709823).
There are three new versions of the sortThis
method: the regular one supporting comparator, one supporting the “by” pattern that takes an extractor function, and a combination of both. This fills the symmetry gap that existed between primitive and object collection APIs.
If the words ‘“by” pattern’ and ‘symmetry gap’ make little sense to you, please see these blogs by Donald Raab for explanation:
- Introducing the concept of Symmetry: Symmetric Sympathy
- More on Symmetry: Finding Symmetry
- “By” methods: By Yourself Some Time
Here are the three new sort API methods on MutableIntList
listed after the old sortThis()
method:
Equivalent APIs have been introduced for all other mutable primitive list types with the exception of MutableBooleanList
, which does not support sorting.
These are some examples of the usage of the new APIs:
The new sort
methods are available starting with the release 10.3 of Eclipse Collections.