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.
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.
Set.iterator() returns value of type Iterator
.
In Kotlin, we can use the iterator()
function to get an iterator and traverse the elements of a set.
For example,
iterator()
function.println
function.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)
}
}
1 2 3 4 5
In Kotlin, we can use the iterator()
function in conjunction with a for loop to traverse the elements of a set.
For example,
iterator()
function.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry")
for (fruit in fruits.iterator()) {
println(fruit)
}
}
apple banana cherry
In Kotlin, the iterator()
function can also be used with mutable sets to traverse and modify the elements.
For example,
iterator()
function.println
function.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)
}
[apple, cherry]
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.