24

now i'm trying to make reversed for a loop.The simple way of reverse for is for(i in start downTo end)

but,what if I use array as a start/end point?

6 Answers 6

65

You can loop from the last index calculated by taking size - 1 to 0 like so:

for (i in array.size - 1 downTo 0) {
    println(array[i])
}

Even simpler, using the lastIndex extension property:

for (i in array.lastIndex downTo 0) {
    println(array[i])
}

Or you could take the indices range and reverse it:

for (i in array.indices.reversed()) {
    println(array[i])
}
5
  • ok, i never thought about that before.it works.thanks for the help sir Commented Aug 19, 2018 at 13:29
  • 4
    About the last one, the one with reversed(), wouldn't it be slower, as it will reverse the array first and then loop through it? Commented Dec 6, 2018 at 4:56
  • 3
    If you look at the bytecode, it actually translates to simple index iteration. There's no need to reverse the array to walk down the indexes.
    – zsmb13
    Commented Dec 7, 2018 at 12:04
  • 0 This is very helpful. I hate the .. doesn't include downTo. I also hate the until is not inclusive, and downTo is inclusive, but there is no upTo or downUntil to make it symmetrical. Just feels really weird and has to be careful with the final index.
    – Tao Zhang
    Commented May 22, 2021 at 18:38
  • Last one is very nice!
    – Yamin
    Commented May 24, 2021 at 2:55
20

Additionally to the first answer from zsmb13, some other variants.

Using IntProgression.reversed:

for (i in (0..array.lastIndex).reversed())
    println("On index $i the value is ${array[i]}")

or using withIndex() together with reversed()

array.withIndex()
        .reversed()
        .forEach{ println("On index ${it.index} the value is ${it.value}")}

or the same using a for loop:

for (elem in array.withIndex().reversed())
    println("On index ${elem.index} the value is ${elem.value}")

or if the index is not needed

for (value in array.reversed())
    println(value)
4

A very clean way in kotlin:

for (i in array.indices.reversed()) {
    println(array[i])
}
1
  • 1
    Kindly do not put code only answer. Putting a description to the code helps beginners understand the context. Commented Mar 5, 2023 at 15:32
1

Just leaving it here in case someone needs it

I created an extension function:

public inline fun <T> Collection<T>.forEachIndexedReversed(action: (index: Int, T) -> Unit): Unit {
    var index = this.size-1
    for (item in this.reversed()) action(index--, item)
}
1
  • 2
    Don't reinvent the wheel bro.
    – Yamin
    Commented May 24, 2021 at 2:56
1
list.reversed().forEachIndexed { index, data ->
    action(data)
}

Test:

val list = listOf("a", "b", "c", "d", "e")
list.reversed().forEachIndexed { index, data ->
    println("$index $data")
}
println("---")
list.withIndex().reversed().forEach {
    println("${it.index} ${it.value}")
}

0 e
1 d
2 c
3 b
4 a
---
4 e
3 d
2 c
1 b
0 a
0

For performance optimal implementation you can use this:

inline fun <T> Array<T>.forEachReverse(action: (T) -> Unit) {
    var index = lastIndex
    while (index >= 0) {
        action(this[index])
        index--
    }
}

It does not create another instance and still uses classical forEach syntax, so you can drop in replace and also is inlined.

For list the same:

inline fun <T> List<T>.forEachReverse(action: (T) -> Unit) {
    var index = size - 1
    while (index >= 0) {
        action(this[index])
        index--
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.