associate With To
Начиная с Kotlin: 1.3
inline fun <K, V, M : MutableMap<in K, in V>> Sequence<K>.associateWithTo(destination: M, valueSelector: (K) -> V): M
Заполняет изменяемую карту destination парами ключ-значение для каждого элемента заданной последовательности и возвращает её; ключом является сам элемент, а значение предоставляется функцией valueSelector, применённой к этому ключу.
Если два элемента равны, последний перезаписывает предыдущее значение в карте.
Операция является терминальной.
Примеры
import kotlin.math.*
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("Jacob", "Bernoulli"))
val withLengthOfNames = mutableMapOf<Person, Int>()
println("withLengthOfNames.isEmpty() is ${withLengthOfNames.isEmpty()}") // true
scientists.associateWithTo(withLengthOfNames) { it.firstName.length + it.lastName.length }
println("withLengthOfNames.isNotEmpty() is ${withLengthOfNames.isNotEmpty()}") // true
// Jacob Bernoulli only occurs once in the map because only the last pair with the same key gets added
println(withLengthOfNames) // {Grace Hopper=11, Jacob Bernoulli=14}
//sampleEnd
}
© 2010–2026 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.sequences/associate-with-to.html