Kotlin List.listIterator()
The Kotlin List.listIterator() function is used to get a list iterator, in proper sequence, over the elements of this list. We can optionally specify the index from which iterator has to start.
Syntax
The syntax of List.listIterator() function is
</>
Copy
list.listIterator()
The syntax to get a list iterator over the elements in this list, starting at the specified index is
</>
Copy
list.listIterator(index: Int)
Examples
In this example, we take a list of integers, and iterate over this list using listIterator() function.
Main.kt
</>
Copy
fun main(args: Array<String>) {
var list = listOf(25, 50, 75, 100)
var iter = list.listIterator()
for (element in iter) {
println(element)
}
}
Output
25
50
75
100
Now, let us given a starting position to listIterator() function as argument. We shall start the iterator from index = 2
.
Main.kt
</>
Copy
fun main(args: Array<String>) {
var list = listOf(25, 50, 75, 100)
var iter = list.listIterator(index = 2)
for (element in iter) {
println(element)
}
}
Output
75
100
Conclusion
In this Kotlin Tutorial, we learned how to get a list iterator over elements of a list, using Kotlin List.listIterator() function.