sortBy
Sorts ascending by a key you extract, instead of writing a comparator by hand.
Lecture
sortBy is sort's
convenience sibling: instead of writing
(a, b) => a.age.compareTo(b.age) yourself, you give
sortBy a key extractor — (a) => a['age'] —
and it sorts by the extracted keys, always ascending, always comparing
them with Comparable.compare.
It is not sort((a, b) => compare(f(a), f(b)))
underneath, and the difference is visible in your callback: that form
would call f twice per comparison — about
2·n·log n times. sortBy extracts each key
exactly once, then sorts by the extracted keys, so an
expensive key extractor costs n calls, not
2·n·log n. Keep f pure and cheap all the same:
the number of calls is guaranteed, the order they happen in is not.
Every guarantee from sort carries over unchanged: the
result is always a new list, never a mutation of the
input. And the same chain-form nuance applies too — on the sync
Fx chain, .sortBy(f) returns another
Fx<T>, so you still need
.toList() to materialize
it, while on the FxAsync chain, .sortBy(f) is
already a terminal returning Future<List<T>>.
sortBy is stable: elements whose keys are
equal keep the order they arrived in, whatever the key type. (Before
0.9.1 that held for int and double keys only —
String and other keys went through List.sort,
which is free to reorder ties.) Stability is what makes a two-level
order possible without a comparator: sort by the secondary key, then by
the primary one.
For descending order use sortByDesc,
which is stable too. For anything beyond chained single keys, drop back
down to sort with an explicit comparator.
Demo 1 · Basics
Demo 2 · Async — already a terminal
Demo 3 · Stable — a two-level order
Try it yourself
Exercise: sort the people by age, youngest first.