🐦 Kotlin
Intermediate
What is associateBy in Kotlin?
Answer
associateBy transforms a collection into a Map where the key for each element is derived by a key selector function. Example: val usersById = users.associateBy { it.id } returns a Map<Int, User>. If multiple elements share the same key, only the last one is kept. Use associate { element -> key to value } for full control over both key and value. For a Map where each key maps to a List of values (like groupBy), use groupBy instead of associateBy.