Kotlin List listIterator()
Syntax & Examples
Syntax of List.listIterator()
There are 2 variations for the syntax of List.listIterator() function. They are:
1.
abstract fun listIterator(): ListIterator<E>
This function returns a list iterator over the elements in this list (in proper sequence).
2.
abstract fun listIterator(index: Int): ListIterator<E>
This function returns a list iterator over the elements in this list (in proper sequence), starting at the specified index.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing the elements'a', 'b', 'c'
. - We obtain a list iterator over
list1
using the ListlistIterator()
function. - We iterate over the elements using a
while
loop, checking if the iterator has more elements withhasNext()
and retrieving each element withnext()
. - 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 listIterator1 = list1.listIterator()
while (listIterator1.hasNext()) {
val element = listIterator1.next()
println(element)
}
}
Output
a b c
2 Example
In this example,
- We create a list named
list2
containing the integers10, 20, 30
. - We obtain a list iterator over
list2
starting at index1
using the ListlistIterator(index: Int)
function. - We iterate over the elements using a
while
loop, checking if the iterator has more elements withhasNext()
and retrieving each element withnext()
. - 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 listIterator2 = list2.listIterator(1)
while (listIterator2.hasNext()) {
val element = listIterator2.next()
println(element)
}
}
Output
20 30
Summary
In this Kotlin tutorial, we learned about listIterator() function of List: the syntax and few working examples with output and detailed explanation for each example.