To iterate over values in a map in Kotlin, you can use the values property along with a for loop or the forEach method. This allows you to access each value in the map.
We can iterate over values in a map in Kotlin using a for loop with the values property, which provides a convenient syntax for iterating over all values in the map.
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.println
function to verify that we are iterating over all values.fun main() {
// Declare and initialize a map
val myMap = mapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Iterate over values using for loop
for (value in myMap.values) {
println(value)
}
}
1 2 3
We can iterate over values in a map in Kotlin using the forEach method, which provides a flexible way to access each value in the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.forEach
method to iterate over the key-value pairs in the map.forEach
, we access each value.println
function to verify that we are iterating over all values.fun main() {
// Declare and initialize a map
val myMap = mapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Iterate over values using forEach method
myMap.forEach { (_, value) ->
println(value)
}
}
1 2 3
We can store values in a separate list and then iterate over the list in Kotlin, which provides a way to work with values independently of their keys.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.values
to store the values from the map.values
property to get a collection of the values in the map and convert it to a list using the toList
method.values
list and print each value to the console using the println
function to verify that we have stored all values separately.fun main() {
// Declare and initialize a map
val myMap = mapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Store values in a separate list
val values = myMap.values.toList()
// Iterate over the values list
for (value in values) {
println(value)
}
}
1 2 3
In this tutorial, we learned How to Iterate Over Values in a Map in Kotlin language with well detailed examples.