The 'associateBy' function in Kotlin allows you to transform a collection into a map by associating each element with a key derived from it. This is particularly useful when you want to quickly look up elements by a specific property without having to iterate through the collection multiple times.
data class User(val id: Int, val name: String)
val users = listOf(
User(1, "Alice"),
User(2, "Bob"),
User(3, "Charlie")
)
// Create a map with user IDs as keys
val userMap = users.associateBy { it.id }
// Accessing a user by ID
val user = userMap[2] // Returns User(id=2, name="Bob")