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

countWhere

How many match? One walk, one number — filter + size, fused.

int countWhere<A>(bool Function(A a) f, Iterable<A> iterable) Future<int> countWhereAsync<A>(FutureOr<bool> Function(A a) f, FxAsyncIterable<A> iterable) int Fx<T>.countWhere(bool Function(T a) f) // chain (sync) Future<int> FxAsync<T>.countWhere(FutureOr<bool> Function(T a) f) // chain (async)

Lecture

"How many of these are overdue / on sale / even?" kept getting written as filter(pred).size() — two chain steps and a lazy intermediate for what is conceptually a single fold. countWhere(pred) is that fold: it walks the pipeline once, increments on each match, and returns the count. Nothing is materialized along the way.

Reach for countBy when you want counts per key (a map of them), and countWhere when one predicate's count is the whole answer. The async twin awaits its predicate per element, like every *Async operator.

Dart-native addition — the shape of Kotlin's count { }.

Demo 1 · One predicate, one number

Demo 2 · Async

Try it yourself

Exercise: count the fallback prices without a filter.

Related: countBy — counts per key · size/count — count everything · filter — when you need the matches themselves