Iterate list in reverse order in Kotlin
This post will discuss various ways to iterate a list in Kotlin in reverse order without actually reversing the list.
1. Using toString() function
If you want to display the contents of the list in reverse order, you can get a reversed read-only view of the original List using the asReversed() function and then print its string representation using the toString() function.
|
1 2 3 4 5 |
fun main() { val list: List<String> = listOf("One", "Two", "Three") println(list.asReversed().toString()) } |
2. Using ListIterator
You can use a special iterator ListIterator, that additionally allows bidirectional access over a normal iterator. It takes the starting position on the list.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val list = listOf("One", "Two", "Three") // start with the end of the list val itr: ListIterator<String> = list.listIterator(list.size) // `hasPrevious()` returns true if the list has a previous element while (itr.hasPrevious()) { println(itr.previous()) } } |
3. Using loop
Since List is an ordered collection, you can use index-based for-loop to access elements by their index in the list. To print the list backward, you can do like:
|
1 2 3 4 5 6 7 |
fun main() { val list = listOf("One", "Two", "Three") for (i in list.indices.reversed()) { println(list[i]) } } |
You can also call the forEach() function on the reversed read-only view of the original List to print each list element in reverse order.
|
1 2 3 4 5 |
fun main() { val list: List<String> = listOf("One", "Two", "Three") list.asReversed().forEach { println(it) } } |
That’s all about iterating a list 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 :)