The syntax of Map.iterator() extension function is:
operator fun <K, V> Map<out K, V>.iterator(): Iterator<Entry<K, V>>
This iterator() extension function of Map returns an Iterator over the entries in the Map.
In this example,
map1
containing key-value pairs.map1
using the iterator()
function.fun main(args: Array<String>) {
val map1 = mapOf("a" to 1, "b" to 2, "c" to 3)
val iterator = map1.iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
println(entry.key + "=" + entry.value)
}
}
a=1 b=2 c=3
In this example,
map3
containing key-value pairs.map3
using the iterator()
function.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val iterator = map3.iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
println(entry.key + "=" + entry.value)
}
}
apple=1 banana=2 cherry=3
In this Kotlin tutorial, we learned about iterator() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.