Kotlin List iterator()
Syntax & Examples


Syntax of List.iterator()

The syntax of List.iterator() function is:

abstract fun iterator(): Iterator<E>

This iterator() function of List returns an iterator over the elements of this object.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the elements 'a', 'b', 'c'.
  • We obtain an iterator over list1 using the List iterator() function.
  • We iterate over the elements using a while loop, checking if the iterator has more elements with hasNext() and retrieving each element with next().
  • Each element is printed to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c")
    val iterator = list1.iterator()
    while (iterator.hasNext()) {
        val element = iterator.next()
        println(element)
    }
}

Output

a
b
c

2 Example

In this example,

  • We create a list named list2 containing the integers 10, 20, 30.
  • We obtain an iterator over list2 using the List iterator() function.
  • We iterate over the elements using a for loop, which internally uses the iterator to access each element.
  • Each element is printed to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list2 = listOf(10, 20, 30)
    val iterator = list2.iterator()
    for (item in iterator) {
        println(item)
    }
}

Output

10
20
30

Summary

In this Kotlin tutorial, we learned about iterator() function of List: the syntax and few working examples with output and detailed explanation for each example.