Convert a map to an array in Kotlin
This article explores different ways to convert a map to an array of key/value pairs in Kotlin.
1. Using toTypedArray() function
The easiest solution to get an array of key/value pairs in Kotlin is by calling the toList() function on the map first, followed by the toTypedArray() function.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val map: MutableMap<String, Int> = HashMap() map["one"] = 1 map["two"] = 2 map["three"] = 3 val array: Array<Pair<String, Int>> = map.toList().toTypedArray(); println(array.contentToString()) // [(one, 1), (two, 2), (three, 3)] } |
2. Using entries properties
The Map’s entries properties return a set of all key/value pairs in the map. To get an array of key/value pairs, you can use the map() function, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val map: MutableMap<String, Int> = HashMap() map["one"] = 1 map["two"] = 2 map["three"] = 3 val array: Array<Pair<String, Int>> = map.entries.map { Pair(it.key, it.value) } .toTypedArray() println(array.contentToString()) // [(one, 1), (two, 2), (three, 3)] } |
3. Using keys properties
The Map’s keys properties return a set of all keys present on the map. To get an array of key/value pairs, you can use the map() function, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val map: MutableMap<String, Int> = HashMap() map["one"] = 1 map["two"] = 2 map["three"] = 3 val array: Array<Pair<String, Int>> = map.keys.map { Pair(it, map[it]!!) } .toTypedArray() println(array.contentToString()) // [(one, 1), (two, 2), (three, 3)] } |
That’s all about converting a map to an array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)