I have a string array and an integer array. How do I create a map using the first as keys and the second as values?
val keys = arrayOf("butter", "milk", "apples") val values = arrayOf(5, 10, 42) val map: Map<String, Int> = ???
How to convert List to Map in Kotlin? doesn't solve this problem; I have 2 arrays and want a single map.
To map multiple arrays with JavaScript, we can use the map method. to define the zip function that calls a1. map to combine the entries from a1 and a2 with index i into one entry. Then we call zip with arr1 and arr2 to zip them into one array.
To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.
Use the spread syntax (...) to merge arrays in React, e.g. const arr3 = [...arr1, ...arr2] . The spread syntax is used to unpack the values of two or more arrays into a new array. The same approach can be used to merge two or more arrays when setting the state.
C++ allows us a facility to create an array of maps. An array of maps is an array in which each element is a map on its own.
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>>
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With