How do filter and sort work together in EK9 streams?
← Streams and Pipelines · Ref: Q929
Chain filter and sort with the pipe operator. Filter first to reduce the dataset, then sort the remaining elements.
PATTERN
cat items | filter by predicate | sort | collect as List of T cat items | filter by predicate | sort > stdout
FILTER narrows the stream to elements matching the predicate (a function returning Boolean). SORT orders the remaining elements using their natural ordering (the <=> operator).
WITH STRINGS
cat names | filter by startsWithA | sort > stdout
Filters to names starting with 'A', then alphabetically sorts them.
WITH FLOATS
cat temperatures | filter by aboveFreezing | sort | collect as List of Float
Keeps temperatures above zero, sorts ascending.
Filtering before sorting is more efficient: sort operates on fewer elements.
See Q235 for all stream operations. See Q896 for output redirection. See Q237 for streams vs loops.
Example
defines module qa.streams.filter.sort.example defines function aboveFreezing() as pure -> temperature as Float <- rtn as Boolean: temperature > 0.0 isLongName() as pure -> nameToCheck as String <- rtn as Boolean? minLength <- 4 rtn: length nameToCheck > minLength defines program FilterSortDemo() stdout <- Stdout() //Demonstrate filter predicates that streams would use stdout.println(`15.5 above freezing: ${aboveFreezing(15.5)}`) stdout.println(`-3.2 above freezing: ${aboveFreezing(-3.2)}`) //Demonstrate string predicate for stream filter stdout.println(`James is long: ${isLongName("James")}`) stdout.println(`Bob is long: ${isLongName("Bob")}`)
Other ways to ask this
- Can I chain filter and sort in an EK9 stream?
- How do I filter then sort a list in EK9?
- What is the correct order for filter and sort in EK9 pipelines?
Coming from another language?
Java: stream().filter(pred).sorted().collect(). Python: sorted(filter(pred, items)). Rust: iter().filter(pred).sorted(). EK9: cat items | filter by pred | sort | collect.
Keywords: stream, filter, order, chain, pipeline, sort, predicate