To reverse a list in Kotlin, you can use the built-in reversed()
function or manually reverse the list by iterating over it and swapping elements from both ends.
In this example,
originalList
containing elements in the original order.reversed()
function to create a reversed version of the list.fun main() {
val originalList = listOf(1, 2, 3, 4, 5)
val reversedList = originalList.reversed()
println("Reversed list: $reversedList")
}
Reversed list: [5, 4, 3, 2, 1]
In this example,
originalList
containing elements in the original order.fun main() {
val originalList = mutableListOf(1, 2, 3, 4, 5)
var start = 0
var end = originalList.size - 1
while (start < end) {
val temp = originalList[start]
originalList[start] = originalList[end]
originalList[end] = temp
start++
end--
}
println("Reversed list: $originalList")
}
Reversed list: [5, 4, 3, 2, 1]
In this tutorial, we learned How to Reverse a List in Kotlin language with well detailed examples.