associate

Common
JVM
JS
Native
1.0
inline fun <T, K, V> Array<out T>.associate(
    transform: (T) -> Pair<K, V>
): Map<K, V>
inline fun <K, V> ByteArray.associate(
    transform: (Byte) -> Pair<K, V>
): Map<K, V>
inline fun <K, V> ShortArray.associate(
    transform: (Short) -> Pair<K, V>
): Map<K, V>
inline fun <K, V> IntArray.associate(
    transform: (Int) -> Pair<K, V>
): Map<K, V>
inline fun <K, V> LongArray.associate(
    transform: (Long) -> Pair<K, V>
): Map<K, V>
inline fun <K, V> FloatArray.associate(
    transform: (Float) -> Pair<K, V>
): Map<K, V>
inline fun <K, V> DoubleArray.associate(
    transform: (Double) -> Pair<K, V>
): Map<K, V>
inline fun <K, V> BooleanArray.associate(
    transform: (Boolean) -> Pair<K, V>
): Map<K, V>
inline fun <K, V> CharArray.associate(
    transform: (Char) -> Pair<K, V>
): Map<K, V>

Returns a Map containing key-value pairs provided by transform function applied to elements of the given array.

If any of two pairs would have the same key the last one gets added to the map.

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

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val charCodes = intArrayOf(72, 69, 76, 76, 79)

val byCharCode = charCodes.associate { it to Char(it) }

// 76=L only occurs once because only the last pair with the same key gets added
println(byCharCode) // {72=H, 69=E, 76=L, 79=O}
//sampleEnd
}
Common
JVM
JS
Native
1.0
inline fun <T, K, V> Iterable<T>.associate(
    transform: (T) -> Pair<K, V>
): Map<K, V>

Returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.

If any of two pairs would have the same key the last one gets added to the map.

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

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val names = listOf("Grace Hopper", "Jacob Bernoulli", "Johann Bernoulli")

val byLastName = names.associate { it.split(" ").let { (firstName, lastName) -> lastName to 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
}