associateBy
Returns a Map containing the elements from the given array indexed by the key returned from keySelector function applied to each element.
If any two elements would have the same key returned by keySelector the last one gets added to the map.
The returned map preserves the entry iteration order of the original array.
Since Kotlin
1.0Samples
import kotlin.test.*
fun main() {
//sampleStart
val charCodes = intArrayOf(72, 69, 76, 76, 79)
val byChar = charCodes.associateBy { Char(it) }
// L=76 only occurs once because only the last pair with the same key gets added
println(byChar) // {H=72, E=69, L=76, O=79}
//sampleEnd
}
Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given array.
If any two elements would have the same key returned by keySelector the last one gets added to the map.
The returned map preserves the entry iteration order of the original array.
Since Kotlin
1.0Samples
import kotlin.test.*
fun main() {
//sampleStart
val charCodes = intArrayOf(65, 65, 66, 67, 68, 69)
val byUpperCase = charCodes.associateBy({ Char(it) }, { Char(it + 32) })
// A=a only occurs once because only the last pair with the same key gets added
println(byUpperCase) // {A=a, B=b, C=c, D=d, E=e}
//sampleEnd
}
Returns a Map containing the elements from the given collection indexed by the key returned from keySelector function applied to each element.
If any two elements would have the same key returned by keySelector the last one gets added to the map.
The returned map preserves the entry iteration order of the original collection.
Since Kotlin
1.0Samples
import kotlin.test.*
fun main() {
//sampleStart
data class Person(val firstName: String, val lastName: String) {
override fun toString(): String = "$firstName $lastName"
}
val scientists = listOf(Person("Grace", "Hopper"), Person("Jacob", "Bernoulli"), Person("Johann", "Bernoulli"))
val byLastName = scientists.associateBy { it.lastName }
// Jacob Bernoulli does not occur in the map because only the last pair with the same key gets added
println(byLastName) // {Hopper=Grace Hopper, Bernoulli=Johann Bernoulli}
//sampleEnd
}
Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection.
If any two elements would have the same key returned by keySelector the last one gets added to the map.
The returned map preserves the entry iteration order of the original collection.
Since Kotlin
1.0Samples
import kotlin.test.*
fun main() {
//sampleStart
data class Person(val firstName: String, val lastName: String)
val scientists = listOf(Person("Grace", "Hopper"), Person("Jacob", "Bernoulli"), Person("Johann", "Bernoulli"))
val byLastName = scientists.associateBy({ it.lastName }, { it.firstName })
// Jacob Bernoulli does not occur in the map because only the last pair with the same key gets added
println(byLastName) // {Hopper=Grace, Bernoulli=Johann}
//sampleEnd
}