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