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>>.
If you need descending order, or a multi-key sort, drop back down to
sort with an explicit comparator — sortBy only
covers the common "ascending by one extracted key" case.
Demo 1 · Basics
Demo 2 · Async — already a terminal
Try it yourself
Exercise: sort the people by age, youngest first.