Kotlin Tutorials

Kotlin Map iterator()
Syntax & Examples

Syntax of Map.iterator()

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.



✐ Examples

1 Iterating over a map of integers

In this example,

  • We create a map named map1 containing key-value pairs.
  • We obtain an iterator over map1 using the iterator() function.
  • We iterate over the map using a while loop, printing each key-value pair to the standard output.

Kotlin Program

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)
    }
}

Output

a=1
b=2
c=3

2 Iterating over a map of strings

In this example,

  • We create a map named map3 containing key-value pairs.
  • We obtain an iterator over map3 using the iterator() function.
  • We iterate over the map using a while loop, printing each key-value pair to the standard output.

Kotlin Program

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)
    }
}

Output

apple=1
banana=2
cherry=3

Summary

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.