Kotlin List.iterator() Function

The Kotlin List.iterator() function returns an iterator object for the elements in list.

Syntax of List.iterator()

The syntax of List.iterator() function is

List.iterator()

Return Value

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

Example 1: Get Iterator over Elements of List

In this example, we will take a list with some strings, get its iterator and use it to print the elements of list.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd", "de")
    val iterator = list1.iterator()
    iterator.forEach {
        println(it)
    }
}

Output

ab
bc
cd
de

Conclusion

In this Kotlin Tutorial, we learned how to get the iterator over the elements of given list, using Kotlin List.iterator() function.