To iterate over a list in reverse order in Kotlin, you can use the listIterator
method combined with the hasPrevious
and previous
functions of the ListIterator
class.
In this example,
listOfNumbers
containing integer values.listIterator
method on listOfNumbers
.hasPrevious
function to iterate over the list in reverse order.previous
function to access each element and print it to standard output.fun main() {
val listOfNumbers = listOf(1, 2, 3, 4, 5)
val listIterator = listOfNumbers.listIterator(listOfNumbers.size)
while (listIterator.hasPrevious()) {
val number = listIterator.previous()
println(number)
}
}
5 4 3 2 1
In this example,
listOfStrings
containing string values.listIterator
method on listOfStrings
.hasPrevious
function to iterate over the list in reverse order.previous
function to access each element and print it to standard output.fun main() {
val listOfStrings = listOf("apple", "banana", "orange", "grape", "kiwi")
val listIterator = listOfStrings.listIterator(listOfStrings.size)
while (listIterator.hasPrevious()) {
val fruit = listIterator.previous()
println(fruit)
}
}
kiwi grape orange banana apple
In this tutorial, we learned How to Iterate Over a List in Reverse Order in Kotlin language with well detailed examples.