This article explores different ways to iterate over a set in Kotlin.

1. Using forEach() function

In Kotlin, you can easily loop over a set with the help of the forEach() function, as shown below:

Download Code

2. Using foreach Loop

Alternatively, you can use a for-loop or foreach loop to loop through Set.

Download Code

3. Using iterator

You can also call the iterator() that returns an iterator over a set, as shown below:

Download Code

 
Or replace the while loop with forEachRemaining() function.

Download Code

4. Using implicit toString() function

If you only need to display contents of the Set, you can simply print the string representation of Set, as shown below:

Download Code

That’s all about iterating over a set in Kotlin.