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