Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function applied to each element of the given array and value is the element itself.
If any two elements would have the same key returned by keySelector the last one gets added to the map.
Since Kotlin
1.0Samples
import kotlin.test.*
fun main() {
val charCodes = intArrayOf(72, 69, 76, 76, 79)
val byChar = mutableMapOf<Char, Int>()
println("byChar.isEmpty() is ${byChar.isEmpty()}")
charCodes.associateByTo(byChar) { Char(it) }
println("byChar.isNotEmpty() is ${byChar.isNotEmpty()}")
println(byChar)
}
Target: JVMRunning on v.2.1.20
Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function and and value is provided by the valueTransform function 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.
Since Kotlin
1.0Samples
import kotlin.test.*
fun main() {
val charCodes = intArrayOf(65, 65, 66, 67, 68, 69)
val byUpperCase = mutableMapOf<Char, Char>()
charCodes.associateByTo(byUpperCase, { Char(it) }, { Char(it + 32) })
println(byUpperCase)
}
Target: JVMRunning on v.2.1.20
Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function applied to each element of the given collection and value is the element itself.
If any two elements would have the same key returned by keySelector the last one gets added to the map.
Since Kotlin
1.0Samples
import kotlin.test.*
fun main() {
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 = mutableMapOf<String, Person>()
println("byLastName.isEmpty() is ${byLastName.isEmpty()}")
scientists.associateByTo(byLastName) { it.lastName }
println("byLastName.isNotEmpty() is ${byLastName.isNotEmpty()}")
println(byLastName)
}
Target: JVMRunning on v.2.1.20
Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function and and value is provided by the valueTransform function 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.
Since Kotlin
1.0Samples
import kotlin.test.*
fun main() {
data class Person(val firstName: String, val lastName: String)
val scientists = listOf(Person("Grace", "Hopper"), Person("Jacob", "Bernoulli"), Person("Johann", "Bernoulli"))
val byLastName = mutableMapOf<String, String>()
println("byLastName.isEmpty() is ${byLastName.isEmpty()}")
scientists.associateByTo(byLastName, { it.lastName }, { it.firstName} )
println("byLastName.isNotEmpty() is ${byLastName.isNotEmpty()}")
println(byLastName)
}
Target: JVMRunning on v.2.1.20