W3cubDocs

/Kotlin

associateByTo

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <T, K, M : MutableMap<in K, in T>> Sequence<T>.associateByTo(
    destination: M, 
    keySelector: (T) -> K
): M

Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function applied to each element of the given sequence and value is the element itself.

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

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 = 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
}
Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <T, K, V, M : MutableMap<in K, in V>> Sequence<T>.associateByTo(
    destination: M, 
    keySelector: (T) -> K, 
    valueTransform: (T) -> V
): M

Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function and and value is provided by the valueTransform function 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 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 = 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
}

© 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-to.html