このページはまだ翻訳されていないため、英語で表示されます。 翻訳に参加する

indexBy

Indexes every element by a computed key into a Map<K, A> — last duplicate wins.

Map<K, A> indexBy<A, K>(K Function(A a) f, Iterable<A> iterable) Future<Map<K, A>> indexByAsync<A, K>(FutureOr<K> Function(A a) f, FxAsyncIterable<A> iterable) Map<K, T> Fx.indexBy<K>(K Function(T a) f) // chain (sync) Future<Map<K, T>> FxAsync.indexBy<K>(FutureOr<K> Function(T a) f) // chain (async)

Lecture

indexBy is groupBy's sibling: same idea — pull the whole pipeline, compute a key for each element — but instead of collecting a list per key, it keeps exactly one value per key: Map<K, A> rather than Map<K, List<A>>.

That means duplicates don't accumulate — they overwrite. If two elements produce the same key, whichever one is processed last (i.e. appears later in the iterable) is the one left in the map. This is the natural behavior of repeatedly doing result[key(a)] = a while walking forward, and it matches FxTS. Reach for indexBy specifically when you know keys should be unique (like a database ID) and you want direct O(1) lookup instead of a list you'd have to search.

If you actually expect duplicate keys and want to keep every value, use groupBy instead — it never discards anything.

Demo 1 · Basics & last-wins

Demo 2 · Async

Try it yourself

Exercise: index the users by their id, so you can look one up directly.

Related: groupBy — keeps every duplicate instead of overwriting · countBy — tally instead of keeping the value · fromEntries — build a Map from key/value pairs directly