Kotlin List – Iterate over Elements using Iterator

To iterate over elements of a List in Kotlin, call iterator() function on this List object, and use forEach() on the iterator returned by 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.

ADVERTISEMENT

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.