Kotlin Map - iterator() Function



The Kotlin Map iterator() function is used to return an iterator for traversing elements in a map. Iterators are useful when we need to process each element of the map one by one.

The iterator function simply accepts a map as input, iterates over it, and performs some operations on its elements.

There are the following use cases of the iterator() function:

  • Custom Traversal Logic: It provides fine-grained control over traversal, including conditional checks or early exit.
  • Compatibility: This function works with all Kotlin collection.
  • Mutable Iterators: For mutable collections, the MutableIterator also includes the remove() function to remove elements during iteration safely.

Syntax

Following is the syntax of Kotlin map iterator() function −

val iterator = map.iterator()

Parameters

This function does not accepts any parameters

Return value

This function returns an iterator object of type Iterator<T>. For mutable collection, it returns a MutableIterator<T>.

Example 1

Let's see a basic example of the iterator() function, which iterates over elements of map.

fun main(args: Array<String>) {
   val map= mapOf(1 to "Aman", 2 to "Kumar", 3 to "Gupta", 4 to "Ranchi", 5 to "Jharkhand")

   // Get the iterator
   val iterator = map.iterator()

   // Traverse using iterator functions
   while (iterator.hasNext()) {
      val element = iterator.next()
      println("Element: $element")
   }
}

Output

Following is the output −

Element: 1=Aman
Element: 2=Kumar
Element: 3=Gupta
Element: 4=Ranchi
Element: 5=Jharkhand

Example 2: Removing Element During Iteration

The following example demonstrate the flexibility of iterator() function, when working with mutable collection −

fun main(args: Array<String>) {
   val details = mutableMapOf(
      1 to "Aman", 
      2 to "Kumar", 
      3 to "Gupta", 
      4 to "Ranchi", 
      5 to "Jharkhand"
   )
   val iterator = details.iterator()

   while (iterator.hasNext()) {
      val entry = iterator.next()
      if (entry.key % 2 == 0) {
         // Remove elements with even keys
         iterator.remove()
      }
   }
   println(details)
}

Output

Following is the output −

{1=Aman, 3=Gupta, 5=Jharkhand}

Example 3: Removing String

This is another example of iterator() function to remove value in mutableMap which having length more than 5 character −

fun main(args: Array<String>) {
   val details = mutableMapOf(
      1 to "Aman", 
      2 to "Kumar", 
      3 to "Gupta", 
      4 to "Ranchi", 
      5 to "Jharkhand"
   )
   val iterator = details.iterator()
   // Remove words less than 5 characters
   while (iterator.hasNext()) {
      val entry = iterator.next()
      if (entry.value.length > 5) {
         iterator.remove()
      }
   }
   println(details)
}

Output

Following is the output −

{1=Aman, 2=Kumar, 3=Gupta}
kotlin_maps.htm
Advertisements