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
list1containing the elements'a', 'b', 'c'. - We obtain an iterator over
list1using the Listiterator()function. - We iterate over the elements using a
whileloop, checking if the iterator has more elements withhasNext()and retrieving each element withnext(). - Each element is printed to standard output using the
printlnfunction.
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
list2containing the integers10, 20, 30. - We obtain an iterator over
list2using the Listiterator()function. - We iterate over the elements using a
forloop, which internally uses the iterator to access each element. - Each element is printed to standard output using the
printlnfunction.
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.