Multiple ways to iterate Map in Kotlin with example
Map contains key and value pairs data structure.
This tutorials explains multiple ways to iterate an Map in Kotlin with examples.
Multiple ways to iterate Key and value pair in Kotlin
there are multiple ways to iterate key and value pair in Kotlin.
- use for in loop
map object in for loop iterated with each object, where each object contains key and value pairs.
Key
and value
pairs are printed using $variable
.
fun main() {
val map = HashMap<String, String>();
map["1"] = "one"
map["2"] = "two"
map["3"] = "three"
map["4"] = "four"
map["5"] = "five"
for ((key, value) in map) {
println("$key - $value")
}
}
Output:
1 - one
2 - two
3 - three
4 - four
5 - five
- use forEach loop
map contains forEach that iterates with callback.
Callback contains key and value that iterates and prints the values.
Here is an example
fun main() {
val map = HashMap<String, String>();
map["1"] = "one"
map["2"] = "two"
map["3"] = "three"
map["4"] = "four"
map["5"] = "five"
map.forEach { (key, value) ->
println("$key = $value")
}
}
-
use Iterator function
Map.keys return array of keys, that uses
iterator
to return iterator
iterator.hasNext()
checks whether an element exists to iterate.
iterator.next() returns next element in an array.
an value for a key retrieved using Map[key] function.
Here is an example
fun main() {
val map = HashMap<String, String>();
map["1"] = "one"
map["2"] = "two"
map["3"] = "three"
map["4"] = "four"
map["5"] = "five"
val iterator = map.keys.iterator()
while (iterator.hasNext()) {
val key = iterator.next()
val value = map[key]
println("${key} - $value")
}
}
Output:
1 - one
2 - two
3 - three
4 - four
5 - five