associateWith
Returns a Map where keys are elements from the given array and values are produced by the valueSelector function applied to each element.
If any two elements are equal, the last one gets added to the map.
The returned map preserves the entry iteration order of the original array.
Since Kotlin
1.4Samples
import kotlin.test.*
fun main() {
//sampleStart
val words = listOf("a", "abc", "ab", "def", "abcd")
val withLength = words.associateWith { it.length }
println(withLength.keys) // [a, abc, ab, def, abcd]
println(withLength.values) // [1, 3, 2, 3, 4]
//sampleEnd
}
Returns a Map where keys are elements from the given collection and values are produced by the valueSelector function applied to each element.
If any two elements are equal, the last one gets added to the map.
The returned map preserves the entry iteration order of the original collection.
Since Kotlin
1.3Samples
import kotlin.test.*
fun main() {
//sampleStart
val words = listOf("a", "abc", "ab", "def", "abcd")
val withLength = words.associateWith { it.length }
println(withLength.keys) // [a, abc, ab, def, abcd]
println(withLength.values) // [1, 3, 2, 3, 4]
//sampleEnd
}