Sort a list of Employee records by salary.
← Operators and Expressions · Ref: Q1085
Sort records by one field with a comparator function given to sort:
bySalary() as pure -> left as Employee right as Employee <- rtn as Integer: left.salary <=> right.salary
sorted <- cat staff | sort by bySalary | collect as List of Employee
A plain '| sort' uses the type's own <=>, and 'default operator' generates <=> across all fields in declaration order (name first here). A different ordering for one use is a comparator function given to 'sort by', never a second <=>.
See Q1073 for descending sort. See Q1082 for basic comparison.
Example
defines module qa.operators.sortrecordsbyfield defines record Employee name as String: String() salary as Float: 0.0 Employee() -> name as String salary as Float this.name :=: name this.salary :=: salary default operator defines function bySalary() as pure -> left as Employee right as Employee <- rtn as Integer: left.salary <=> right.salary 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 one field: a comparator function given to sort sorted <- cat staff | sort by bySalary | 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 by comparator | collect as List of T'. See ek9 -h E50060 for details.
Incorrect:
sorted <- staff.sort()
Correct:
sorted <- cat staff | sort by bySalary | 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 by comparator | collect as List of T.
Keywords: ascending, pipeline, order, stream, record, list, sort