Iterators
Iterators can be obtained for inheritors of the interface, including Set
and List
, by calling the function. Once you obtain an iterator, it points to the first element of a collection; calling the next()
function returns this element and moves the iterator position to the following element if it exists. Once the iterator passes through the last element, it can no longer be used for retrieving elements; neither can it be reset to any previous position. To iterate through the collection again, create a new iterator.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
for (item in numbers) {
println(item)
}
//sampleEnd
}
Finally, there is a useful forEach()
function that lets you automatically iterate a collection and execute the given code for each element. So, the same example would look like this:
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val listIterator = numbers.listIterator()
while (listIterator.hasNext()) listIterator.next()
println("Iterating backwards:")
while (listIterator.hasPrevious()) {
print("Index: ${listIterator.previousIndex()}")
println(", value: ${listIterator.previous()}")
}
//sampleEnd
Having the ability to iterate in both directions, means the ListIterator
can still be used after it reaches the last element.
Mutable iterators
In addition to removing elements, the MutableListIterator
can also insert and replace elements while iterating the list.
fun main() {
//sampleStart
val numbers = mutableListOf("one", "four", "four")
val mutableListIterator = numbers.listIterator()
mutableListIterator.next()
mutableListIterator.add("two")
mutableListIterator.next()
mutableListIterator.set("three")
println(numbers)