How do I create a map from 2 arrays?

According to kotlin Constructing Collections -> creating a short-living Pair object, is not recommended only if performance isn't critical and to quote: "To avoid excessive memory usage, use alternative ways. For example, you can create a mutable map and populate it using the write operations. The apply() function can help to keep the initialization fluent here."

since I'm not much of an expert I run on to these code and maybe this should work better?:

    val numbersMap = mutableMapOf<String,Int>()
        .apply{ for (i in 1.. 5)  this["key$i"] = i }
    println(numbersMap)

    //result = {key1=1, key2=2, key3=3, key4=4}

or to adjust it to question above - something like this:

    val keys = arrayOf("butter", "milk", "apples")
    val values = arrayOf(5, 10, 42)
    val mapNumber = mutableMapOf<String, Int>()
            .apply { for (i in keys.indices) this[keys[i]] = values[i] }
    println(mapNumber)

You can zip together the arrays to get a list of pairs (List<Pair<String, Int>>), and then use toMap to get your map.

Like this:

val keys = arrayOf("butter", "milk", "apples")
val values = arrayOf(5, 10, 42)

val map: Map<String, Int> = 
             keys.zip(values) // Gives you [("butter", 5), ("milk", 10), ("apples", 42)]
                 .toMap()     // This is an extension function on Iterable<Pair<K, V>>

Tags:

Kotlin