Sort a list of Employee records by salary.
← Operators and Expressions · Ref: Q1085
Sort records via stream pipeline using default <=>:
sorted <- cat staff | sort | collect as List of Employee
'default operator' generates <=> across all fields in declaration order. For field-specific sorting, implement a custom <=>.
See Q1073 for descending sort. See Q1082 for basic comparison.
Example
defines module qa.operators.sortrecordsbyfield defines class Employee name <- String() salary <- Float() Employee() -> name as String salary as Float this.name :=: name this.salary :=: salary default operator defines program SortRecordsByFieldDemo() stdout <- Stdout() staff <- List() of Employee staff += Employee("Alice", 75000.0) staff += Employee("Bob", 55000.0) staff += Employee("Charlie", 92000.0) staff += Employee("Diana", 68000.0) stdout.println("Unsorted:") cat staff > stdout //Sort by natural ordering (fields in declaration order: name then salary) sorted <- cat staff | sort | collect as List of Employee stdout.println("Sorted:") cat sorted > stdout
Common mistakes
E50060 — EK9 List has no .sort() method; sort via a stream pipeline 'cat list | sort | collect as List of T'. See ek9 -h E50060 for details.
Incorrect:
sorted <- staff.sort()
Correct:
sorted <- cat staff | sort | collect as List of Employee
Other ways to ask this
- Order objects in a list using a stream sort pipeline
- Arrange records from lowest to highest value
- In Java I'd use Collections.sort with Comparator.comparing(). How in EK9?
- I have a list of employees and need to sort them by pay
Coming from another language?
Java: Collections.sort(list, Comparator.comparing(Employee::getSalary)). Python: sorted(employees, key=lambda e: e.salary). Rust: sort_by_key(). EK9: cat list | sort | collect as List of T.
Keywords: stream, order, pipeline, ascending, sort, list, record