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?
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])
}
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
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)
A very clean way in kotlin:
for (i in array.indices.reversed()) {
println(array[i])
}
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)
}
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
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--
}
}