Convert a map in Kotlin to a list of key-value pairs
This article explores different ways to convert a map in Kotlin to a list of key/value pairs.
1. Using toList() function
In Kotlin, you can easily get a list of key/value pairs in this map by calling the toList() function on the map instance.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val hMap: MutableMap<String, Int> = HashMap() hMap["A"] = 65 hMap["B"] = 66 hMap["C"] = 67 val entries: List<Pair<String, Int>> = hMap.toList() println(entries) // [(A, 65), (B, 66), (C, 67)] } |
2. Using entries properties
The Map’s entries properties return a set of all key/value pairs in the map. To convert it to a list, you can use the map() function with the Pair class.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val hMap: MutableMap<String, Int> = HashMap() hMap["A"] = 65 hMap["B"] = 66 hMap["C"] = 67 val entries: List<Pair<String, Int>> = hMap.entries.map { Pair(it.key, it.value) } println(entries) // [(A, 65), (B, 66), (C, 67)] } |
3. Using keys properties
The Map’s keys properties return a set of all keys present on the map. To get the list of key/value pairs, you can use the map() function with the Pair class.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val hMap: MutableMap<String, Int> = HashMap() hMap["A"] = 65 hMap["B"] = 66 hMap["C"] = 67 val entries: List<Pair<String, Int?>> = hMap.keys.map { Pair(it, hMap[it]) } println(entries) // [(A, 65), (B, 66), (C, 67)] } |
That’s all about converting a map in Kotlin to a list of key-value pairs.
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 :)