To convert a map to an array of values in Kotlin, you can use the values property to get a collection of values and then convert this collection to a list. This provides a convenient way to extract all values from the map.
We can convert a map to an array of values in Kotlin using the values property, which provides a collection of all values in the map. We can then convert this collection to a list.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.values
property to get a collection of the values in the map.toList
method.valuesList
.println
function to verify the conversion.fun main() {
// Declare and initialize a map
val myMap = mapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Convert map to an array of values
val valuesList = myMap.values.toList()
// Print the values
println("Values: $valuesList")
}
Values: [1, 2, 3]
We can also convert an empty map to an array of values in Kotlin using the values property, which returns an empty list when the map is empty.
For example,
emptyMap
with string keys and integer values.values
property to get a collection of the values in the empty map.toList
method.emptyValuesList
.println
function to verify that the list is empty.fun main() {
// Declare an empty map
val emptyMap = mapOf<String, Int>()
// Convert empty map to an array of values
val emptyValuesList = emptyMap.values.toList()
// Print the values
println("Values: $emptyValuesList")
}
Values: []
We can convert a map to an array of values in Kotlin after adding elements using the values property, which provides an updated collection of all values in the map.
For example,
dynamicMap
with string keys and integer values.values
property to get a collection of the values in the map after adding elements.toList
method.dynamicValuesList
.println
function to verify the updated list of values.fun main() {
// Declare an empty mutable map
val dynamicMap = mutableMapOf<String, Int>()
// Add elements to the map
dynamicMap["one"] = 1
dynamicMap["two"] = 2
dynamicMap["three"] = 3
// Convert map to an array of values after adding elements
val dynamicValuesList = dynamicMap.values.toList()
// Print the values
println("Values: $dynamicValuesList")
}
Values: [1, 2, 3]
In this tutorial, we learned How to Convert a Map to an Array of Values in Kotlin language with well detailed examples.