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

averageBy

The mean of a key over every element — map + average in one step, NaN when empty.

double averageBy<A>(num Function(A a) f, Iterable<A> iterable) Future<double> averageByAsync<A>(FutureOr<num> Function(A a) f, FxAsyncIterable<A> iterable) double Fx<T>.averageBy(num Function(T a) f) // chain (sync) Future<double> FxAsync<T>.averageBy(FutureOr<num> Function(T a) f) // chain (async)

Lecture

averageBy completes the by-key family (sumBy · maxBy · minBy): it extracts a numeric key from each element and averages the keys, in one walk that tracks a running total and count.

The contract is average's: an empty pipeline returns double.nan (it is computing 0 / 0), never 0 — check result.isNaN when the input can be empty. The result is always a double.

Demo 1 · Basics & the empty case

Demo 2 · Async keys

Try it yourself

Exercise: average only the read books' page counts with one call.

Related: average — when the pipeline already holds numbers · sumBy — the numerator's cousin · maxBy · minBy — the rest of the family