W3cubDocs

/Kotlin

associateBy

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

Returns a Map containing the characters from the given char sequence indexed by the key returned from keySelector function applied to each character.

If any two characters 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 char sequence.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val string = "bonne journée"
// associate each character by its code
val result = string.associateBy { 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> CharSequence.associateBy(
    keySelector: (Char) -> K, 
    valueTransform: (Char) -> V
): Map<K, V>

Returns a Map containing the values provided by valueTransform and indexed by keySelector functions 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.

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

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 = string.associateBy({ 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.html