In this tutorial, you shall learn how to iterate over elements of a given Set in Kotlin using loop statements, with examples.

Kotlin – Iterate over Set

To iterate over elements of Set in Kotlin, we can use for loop, forEach() function, or while loop.

In this tutorial, we will go through these looping techniques and iterate over elements of a Set.

1. Iterate over Set using For loop

In the following example, we will use for loop to iterate over each element of the Set.

Main.kt

fun main(args: Array<String>) {
    var mySet = setOf(1, 4, 9, 16, 25)
    for (element in mySet) {
        println(element)
    }
}

Output

1
4
9
16
25
ADVERTISEMENT

2. Iterate over Set using forEach()

In the following example, we will use forEach() function to iterate over each element of the Set.

Main.kt

fun main(args: Array<String>) {
    var mySet = setOf(1, 4, 9, 16, 25)
    mySet.forEach{
        println(it)
    }
}

Inside forEach() block, we can access the element using the variable name it.

Output

1
4
9
16
25

2. Iterate over Set using While Loop

In the following example, we will use While Loop to iterate over each element of the Set with the help of Set.iterator().

Set.iterator() returns an iterator for this Set. We shall iterate over the Set while this iterator has a next element, meaning iterator.hasNext() is true, and accessing the element in the while block using iterator.next().

Main.kt

fun main(args: Array<String>) {
    var mySet = setOf(1, 4, 9, 16, 25)
    val iterator = mySet.iterator()
    while (iterator.hasNext()) {
        val element = iterator.next()
        println(element)
    }
}

Inside forEach() block, we can access the element using the variable name it.

Output

1
4
9
16
25

Conclusion

In this Kotlin Tutorial, we learned how to iterate over the elements of a Set, using different looping techniques, with the help of examples.