Kotlin Set - iterator() Function



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

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 set iterator() function −

val iterator = Set.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 set.

fun main(args: Array<String>) {
   val fruits = setOf("Apple", "Banana", "Cherry")
   // get the iterator
   val iterator = fruits.iterator()

   while (iterator.hasNext()) {
      println(iterator.next())
   }
}

Output

Following is the output −

Apple
Banana
Cherry

Example 2: Filter a Set

The following example uses the iterator() function, to filters out elements based on a condition −

fun main(args: Array<String>) {
   val numbers = mutableSetOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
   // Get the iterator
   val iterator = numbers.iterator()
   // Remove numbers greater than 5
   while (iterator.hasNext()) {
      val number = iterator.next()
      if (number > 5) {
         iterator.remove()
      }
   }
   println("Filtered Set: $numbers")
}

Output

Following is the output −

Filtered Set: [1, 2, 3, 4, 5]

Example 3: Removing String

This is another example of iterator() function to remove strings having less than 5 character in the mutableSet −

fun main(args: Array<String>) {
   val words = mutableSetOf("Ravi", "Vivek", "Aman", "Amansha", "Sumit", "Sarika")
   
   // Get the iterator
   val iterator = words.iterator()
   
   // Remove words less than 5 characters
   while (iterator.hasNext()) {
      val word = iterator.next()
      if (word.length < 5) {
         iterator.remove()
      }
   }
   println("Filtered Set: $words")
}

Output

Following is the output −

Filtered Set: [Vivek, Amansha, Sumit, Sarika]
kotlin_sets.htm
Advertisements