Kotlin Tutorials

Kotlin Set iterator()
Syntax & Examples

Set.iterator() function

The iterator() function of the Set class in Kotlin returns an iterator over the elements in the set, allowing you to traverse through the elements sequentially.


Syntax of Set.iterator()

The syntax of Set.iterator() function is:

abstract fun iterator(): Iterator<E>

This iterator() function of Set returns an iterator over the elements of this set.

Return Type

Set.iterator() returns value of type Iterator.



✐ Examples

1 Using iterator() to traverse a set

In Kotlin, we can use the iterator() function to get an iterator and traverse the elements of a set.

For example,

  1. Create a set of integers.
  2. Get an iterator for the set using the iterator() function.
  3. Use a while loop to iterate through the elements and print each element to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val numbers = setOf(1, 2, 3, 4, 5)
    val iterator = numbers.iterator()
    while (iterator.hasNext()) {
        val element = iterator.next()
        println(element)
    }
}

Output

1
2
3
4
5

2 Using iterator() with a for loop

In Kotlin, we can use the iterator() function in conjunction with a for loop to traverse the elements of a set.

For example,

  1. Create a set of strings.
  2. Get an iterator for the set using the iterator() function.
  3. Use a for loop to iterate through the elements and print each element to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val fruits = setOf("apple", "banana", "cherry")
    for (fruit in fruits.iterator()) {
        println(fruit)
    }
}

Output

apple
banana
cherry

3 Using iterator() with a mutable set

In Kotlin, the iterator() function can also be used with mutable sets to traverse and modify the elements.

For example,

  1. Create a mutable set of strings.
  2. Add elements to the set.
  3. Get an iterator for the set using the iterator() function.
  4. Use a while loop to iterate through the elements, remove an element, and print the remaining elements to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val mutableSet = mutableSetOf("apple", "banana", "cherry")
    val iterator = mutableSet.iterator()
    while (iterator.hasNext()) {
        val element = iterator.next()
        if (element == "banana") {
            iterator.remove()
        }
    }
    println(mutableSet)
}

Output

[apple, cherry]

Summary

In this Kotlin tutorial, we learned about iterator() function of Set: the syntax and few working examples with output and detailed explanation for each example.