Sort a list of Item records by price and collect the sorted result.
← Streams and Pipelines · Ref: Q1135
To sort by price, give the stream a comparator function and use 'sort by':
sorted <- cat items | sort by comparePrice | collect as List of Item
A bare 'sort' uses the class's 'default operator', which generates <=> comparing fields in declaration order. For Item, name is declared first, so a bare sort orders by name, not price. Use 'sort by' with a comparator (or declare price first) to order by price. See Q1085, Q1073.
Example
defines module qa.streams.streamrecordpipeline defines record Item name as String: String() price as Float: 0.0 Item() -> name as String price as Float this.name :=: name this.price :=: price default operator defines function comparePrice() as pure -> left as Item right as Item <- rtn as Integer: left.price <=> right.price defines program StreamRecordPipelineDemo() stdout <- Stdout() items <- List() of Item items += Item("Monitor", 299.99) items += Item("Mouse", 19.99) items += Item("Keyboard", 49.99) //Sort by price with a comparator (a bare sort would use the default <=> and order by name) sorted <- cat items | sort by comparePrice | collect as List of Item stdout.println("Sorted:") cat sorted > stdout
Common mistakes
E50001 — EK9 uses stream pipelines for sorting: write a comparator function and use cat | sort by comparator.
Incorrect:
items.sort(Comparator.comparing(Item::getPrice))
Correct:
sorted <- cat items | sort by comparePrice | collect as List of Item
Other ways to ask this
- I have product objects and need to sort them by price using a stream
- In Java I'd use stream().sorted(). Write the EK9 record sort pipeline
- Given a list of items with names and prices, sort and output them
- Build a stream pipeline that sorts custom records by their natural ordering
Coming from another language?
Java: stream().sorted(Comparator.comparing(Item::getPrice)). Python: sorted(items, key=lambda x: x.price). EK9: cat items | sort | collect.
Keywords: stream, record, pipeline, sort, order, collect