associate所在位置是kotlin.sequences.associate,其相關用法介紹如下。

用法:

inline fun <T, K, V> Sequence<T>.associate(
    transform: (T) -> Pair<K, V>
): Map<K, V>

返回一個Map,其中包含由transform 函數提供的鍵值對,該函數應用於給定序列的元素。

如果兩對中的任何一對具有相同的 key ,則最後一個將添加到Map中。

返回的映射保留原始序列的條目迭代順序。

操作是 terminal

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val names = listOf("Grace Hopper", "Jacob Bernoulli", "Johann Bernoulli")

val byLastName = names.associate { it.split(" ").let { (firstName, lastName) -> lastName to 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
}

輸出:

{Hopper=Grace, Bernoulli=Johann}