associateByTo所在位置是kotlin.sequences.associateByTo,其相关用法介绍如下。

用法一

inline fun <T, K, M : MutableMap<in K, in T>> Sequence<T>.associateByTo(
    destination: M, 
    keySelector: (T) -> K
): M

使用键值对填充并返回 destination 可变映射,其中键由应用于给定序列的每个元素的 keySelector 函数提供,值是元素本身。

如果任意两个元素具有由keySelector 返回的相同键,则将最后一个元素添加到Map中。

操作是 terminal

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//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 = mutableMapOf<String, Person>()
println("byLastName.isEmpty() is ${byLastName.isEmpty()}") // true

scientists.associateByTo(byLastName) { it.lastName }

println("byLastName.isNotEmpty() is ${byLastName.isNotEmpty()}") // true
// 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
}

输出:

byLastName.isEmpty() is true
byLastName.isNotEmpty() is true
{Hopper=Grace Hopper, Bernoulli=Johann Bernoulli}

用法二

inline fun <T, K, V, M : MutableMap<in K, in V>> Sequence<T>.associateByTo(
    destination: M, 
    keySelector: (T) -> K, 
    valueTransform: (T) -> V
): M

使用键值对填充并返回destination 可变映射,其中键由keySelector 函数提供,值由应用于给定序列元素的valueTransform 函数提供。

如果任意两个元素具有由keySelector 返回的相同键,则将最后一个元素添加到Map中。

操作是 terminal

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
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()}") // true

scientists.associateByTo(byLastName, { it.lastName }, { it.firstName} )

println("byLastName.isNotEmpty() is ${byLastName.isNotEmpty()}") // true
// 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
}

输出:

byLastName.isEmpty() is true
byLastName.isNotEmpty() is true
{Hopper=Grace, Bernoulli=Johann}