W3cubDocs

/Kotlin

associateByTo

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

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

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

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val string = "bonne journée"
// associate each character by its code
val result = mutableMapOf<Int, Char>()
string.associateByTo(result) { char -> char.toInt() }
// notice each char code occurs only once
println(result) // {98=b, 111=o, 110=n, 101=e, 32= , 106=j, 117=u, 114=r, 233=é}
//sampleEnd
}
Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <K, V, M : MutableMap<in K, in V>> CharSequence.associateByTo(
    destination: M, 
    keySelector: (Char) -> K, 
    valueTransform: (Char) -> 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 characters of the given char sequence.

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

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val string = "bonne journée"
// associate each character by the code of its upper case equivalent and transform the character to upper case
val result = mutableMapOf<Int, Char>()
string.associateByTo(result, { char -> char.toUpperCase().toInt() }, { char -> char.toUpperCase() })
// notice each char code occurs only once
println(result) // {66=B, 79=O, 78=N, 69=E, 32= , 74=J, 85=U, 82=R, 201=É}
//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.text/associate-by-to.html