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.

    1. fun main() {
    2. //sampleStart
    3. val numbers = listOf("one", "two", "three", "four")
    4. for (item in numbers) {
    5. println(item)
    6. }
    7. //sampleEnd
    8. }

    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:

    1. //sampleStart
    2. val numbers = listOf("one", "two", "three", "four")
    3. val listIterator = numbers.listIterator()
    4. while (listIterator.hasNext()) listIterator.next()
    5. println("Iterating backwards:")
    6. while (listIterator.hasPrevious()) {
    7. print("Index: ${listIterator.previousIndex()}")
    8. println(", value: ${listIterator.previous()}")
    9. }
    10. //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.

    1. fun main() {
    2. //sampleStart
    3. val numbers = mutableListOf("one", "four", "four")
    4. val mutableListIterator = numbers.listIterator()
    5. mutableListIterator.next()
    6. mutableListIterator.add("two")
    7. mutableListIterator.next()
    8. mutableListIterator.set("three")
    9. println(numbers)