How do I sort a stream in descending order in EK9?
← Streams and Pipelines · Ref: Q1073
EK9 has two sort forms in stream pipelines:
1. 'sort' — uses the natural ordering (ascending via <=> operator)
2. 'sort by comparatorFunction' — uses a custom comparator function
ASCENDING (natural order):
cat scores | sort | head 3 | collect as List of Integer
DESCENDING (custom comparator):
cat scores | sort by descending | head 3 | collect as List of Integer
The comparator function must take two parameters of the same type and return Integer:
descending() as pure -> left as Integer, right as Integer <- rtn as Integer: right <=> left
Note: right <=> left reverses the order (compare right to left instead of left to right).
For ascending, left <=> right. For descending, right <=> left.
You can also use 'tail N' with ascending sort to get the N largest:
cat scores | sort | tail 3 | collect as List of Integer
See Q979 for sort by examples. See Q120 for collection sorting. See Q235 for complete stream operations.
Example
defines module qa.streams.sortdescending defines function //Descending comparator: reverse the <=> order descending() as pure -> left as Integer right as Integer <- rtn as Integer: right <=> left defines program SortDemo() stdout <- Stdout() scores <- [85, 42, 91, 67, 73, 55, 88, 96, 61, 79] stdout.println(`All: ${scores}`) //Top 3 largest: sort descending with comparator, take head topThree <- cat scores | sort by descending | head 3 | collect as List of Integer stdout.println(`Top 3: ${topThree}`) //Bottom 3 smallest: sort ascending (natural), take head bottomThree <- cat scores | sort | head 3 | collect as List of Integer stdout.println(`Bottom 3: ${bottomThree}`)
Other ways to ask this
- Can I reverse sort a stream pipeline?
- How do I get the top N largest items from a list?
- How does sort by work with a comparator function?
Coming from another language?
Java: stream().sorted(Comparator.reverseOrder()). Python: sorted(items, reverse=True). Rust: sort().rev(). EK9: sort by with reversed comparator (right <=> left).
Keywords: head, stream, reverse, pipeline, descending, sort, comparator