Iterate through an array in reverse order in Kotlin
This article explores different ways to iterate through an array in reverse order in Kotlin.
1. Using reversed() function
In Kotlin, you can easily create ranges of values using the rangeTo() function and its operator form ... The idea is to create a range of array indices and reverse it using the reversed() function.
|
1 2 3 4 5 6 |
fun main() { val array: IntArray = intArrayOf(1, 2, 3, 4, 5) for (i in (0..array.lastIndex).reversed()) { println("Index ${i}, Value ${array[i]}") } } |
You can shorten the code using the indices property, which returns the range of valid indices for the array.
|
1 2 3 4 5 6 |
fun main() { val array: IntArray = intArrayOf(1, 2, 3, 4, 5) for (i in array.indices.reversed()) { println("Index ${i}, Value ${array[i]}") } } |
If the index is not needed, you can call the reversed() function on the array like:
|
1 2 3 4 5 6 7 |
fun main() { val array: IntArray = intArrayOf(1, 2, 3, 4, 5) for (i in array.reversed()) { println(i) } } |
You can even start the loop at the last index of the array and use the downTo function with step -1.
|
1 2 3 4 5 6 7 |
fun main() { val array: IntArray = intArrayOf(1, 2, 3, 4, 5) for (i in array.lastIndex downTo 0) { println("Index ${i}, Value ${array[i]}") } } |
2. Using withIndex() function
Alternatively, you can use the withIndex() library function. It returns a lazy Iterable that wraps each element of the original array into an IndexedValue containing the index of that element and the element itself.
The following solution use withIndex() function together with reversed() to iterate through an array in reverse order.
|
1 2 3 4 5 6 |
fun main() { val array: IntArray = intArrayOf(1, 2, 3, 4, 5) array.withIndex().reversed() .forEach{ println("Index ${it.index}, Value ${it.value}") } } |
Following is the equivalent version using a for loop:
|
1 2 3 4 5 6 7 |
fun main() { val array: IntArray = intArrayOf(1, 2, 3, 4, 5) for (it in array.withIndex().reversed()) { println("Index ${it.index}, Value ${it.value}") } } |
3. Reverse Copy
You can even create a reverse copy of an array. The idea is to create a range of array indices and map the values of the original array in reverse order. Finally, accumulate the reversed elements into the corresponding array. This would translate to a simple code below:
|
1 2 3 4 5 6 7 8 9 |
fun main() { val array: IntArray = intArrayOf(1, 2, 3, 4, 5) val reverse = (0.. array.lastIndex) .map { array[array.lastIndex - it] } .toIntArray() println(reverse.contentToString()) // [5, 4, 3, 2, 1] } |
That’s all about iterating an array in reverse order in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)