associateBy
所在位置是kotlin.sequences.associateBy
,其相关用法介绍如下。
用法一
返回一个Map,其中包含给定序列中的元素,该序列由应用于每个元素的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 = scientists.associateBy { it.lastName }
// 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
}
输出:
{Hopper=Grace Hopper, Bernoulli=Johann Bernoulli}
用法二
inline fun <T, K, V> Sequence<T>.associateBy(
keySelector: (T) -> K,
valueTransform: (T) -> V
): Map<K, V>
返回一个 Map,其中包含由 valueTransform 提供的值,并由应用于给定序列元素的 keySelector 函数索引。
如果任意两个元素具有由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 = scientists.associateBy({ it.lastName }, { it.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}
相关用法
- Kotlin associateBy用法及代码示例
- Kotlin associateByTo用法及代码示例
- Kotlin associateWithTo用法及代码示例
- Kotlin associate用法及代码示例
- Kotlin associateTo用法及代码示例
- Kotlin associateWith用法及代码示例
- Kotlin asSequence用法及代码示例
- Kotlin asReversed用法及代码示例
- Kotlin all用法及代码示例
- Kotlin any用法及代码示例
- Kotlin aggregateTo用法及代码示例
- Kotlin aggregate用法及代码示例
- Kotlin map用法及代码示例
- Kotlin filterNot用法及代码示例
- Kotlin reduceRight用法及代码示例
- Kotlin Random.Default用法及代码示例
- Kotlin Byte.inc用法及代码示例
- Kotlin getValue用法及代码示例
- Kotlin Double.dec用法及代码示例
- Kotlin windowedSequence用法及代码示例
- Kotlin contentToString用法及代码示例
- Kotlin groupByTo用法及代码示例
- Kotlin commonPrefixWith用法及代码示例
- Kotlin MatchResult.Destructured用法及代码示例
- Kotlin Delegates.notNull用法及代码示例
注:本文由纯净天空筛选整理自kotlinlang.org大神的英文原创作品 kotlin.sequences.associateBy。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。