W3cubDocs

/Kotlin

associateBy

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <T, K> Sequence<T>.associateBy(
    keySelector: (T) -> K
): Map<K, T>

Returns a Map containing the elements from the given sequence indexed by the key returned from keySelector function applied to each element.

If any two elements would have the same key returned by keySelector the last one gets added to the map.

The returned map preserves the entry iteration order of the original sequence.

The operation is 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
}
Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <T, K, V> Sequence<T>.associateBy(
    keySelector: (T) -> K, 
    valueTransform: (T) -> V
): Map<K, V>

Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given sequence.

If any two elements would have the same key returned by keySelector the last one gets added to the map.

The returned map preserves the entry iteration order of the original sequence.

The operation is 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
}

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/associate-by.html