Iterate over a set in Kotlin
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:
|
1 2 3 4 5 |
fun main() { val set: Set<Int> = setOf(1, 2, 3, 4, 5) set.forEach { println(it) } } |
2. Using foreach Loop
Alternatively, you can use a for-loop or foreach loop to loop through Set.
|
1 2 3 4 5 6 7 |
fun main() { val set: Set<Int> = setOf(1, 2, 3, 4, 5) for (item in set) { println(item) } } |
3. Using iterator
You can also call the iterator() that returns an iterator over a set, as shown below:
|
1 2 3 4 5 6 7 8 |
fun main() { val set: Set<Int> = setOf(1, 2, 3, 4, 5) val it = set.iterator() while (it.hasNext()) { println(it.next()) } } |
Or replace the while loop with forEachRemaining() function.
|
1 2 3 4 5 |
fun main() { val set: Set<Int> = setOf(1, 2, 3, 4, 5) set.iterator().forEachRemaining { println(it) } } |
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:
|
1 2 3 4 5 6 |
fun main() { val set: Set<Int> = setOf(1, 2, 3, 4, 5) // Print string representation of the set println(set) } |
That’s all about iterating over a set in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)