本页尚未翻译,因此以英文显示。 参与翻译

maxBy

The element whose key is largest — one walk, no sort, null when empty.

A? maxBy<A>(Object? Function(A a) f, Iterable<A> iterable) Future<A?> maxByAsync<A>(Object? Function(A a) f, FxAsyncIterable<A> iterable) T? Fx<T>.maxBy(Object? Function(T a) f) // chain (sync) Future<T?> FxAsync<T>.maxBy(Object? Function(T a) f) // chain (async)

Lecture

maxBy answers "which element has the biggest key?" — not "what is the biggest number?" (that's max). It walks the pipeline once, keeping the current best element, so it is O(n) where the tempting sortBy(key).head() shape pays O(n log n) and materializes a sorted list it never needs.

Keys are compared exactly like sortBy compares them (Comparable.compare), and on ties the first element encountered wins — so maxBy over a date-sorted list gives you the earliest of the equally-largest.

Empty input returns null, like head and last — Dart's nullable types replace FxTS's undefined here. This is a Dart-native addition (FxTS only ships the numeric max); the name follows Kotlin's maxByOrNull shape.

Demo 1 · Basics, empty case & ties

Demo 2 · Async

Try it yourself

Exercise: find the biggest expense without sorting.

Related: minBy — the mirror image · max — when you want the key itself, not the element · sortBy — when you need the full ordering anyway