indexBy
Indexes every element by a computed key into a Map<K, A> — last duplicate wins.
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.
groupBy — keeps every duplicate instead of overwriting ·
countBy — tally instead of keeping the value ·
fromEntries — build a Map from key/value pairs directly