associateBy

inline fun <K> CharSequence.associateBy(keySelector: (Char) -> K): Map<K, Char>(source)

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.

Since Kotlin

1.0

Samples

import java.util.Locale
import kotlin.test.*

fun main() { 
   //sampleStart 
   val string = "bonne journée"
// associate each character by its code
val result = string.associateBy { char -> char.code }
// 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
}

inline fun <K, V> CharSequence.associateBy(keySelector: (Char) -> K, valueTransform: (Char) -> V): Map<K, V>(source)

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.

Since Kotlin

1.0

Samples

import java.util.Locale
import kotlin.test.*

fun main() { 
   //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.uppercaseChar().code }, { char -> char.uppercaseChar() })
// 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
}