Kotlin List reversed()
Syntax & Examples
Syntax of List.reversed()
The syntax of List.reversed() extension function is:
fun <T> Iterable<T>.reversed(): List<T>
This reversed() extension function of List returns a list with elements in reversed order.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing the integers[1, 2, 3, 4, 5]
. - We use the
reversed
function to reverse the order of elements in the list. - The reversed list is stored in a variable named
reversedList
. - Finally, we print the reversed list to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val reversedList = list.reversed();
println(reversedList);
}
Output
[5, 4, 3, 2, 1]
2 Example
In this example,
- We create a list named
list
containing the characters['a', 'b', 'c', 'd', 'e']
. - We use the
reversed
function to reverse the order of elements in the list. - The reversed list is stored in a variable named
reversedList
. - Finally, we print the reversed list to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c', 'd', 'e');
val reversedList = list.reversed();
println(reversedList);
}
Output
[e, d, c, b, a]
3 Example
In this example,
- We create a list named
list
containing the strings['apple', 'banana', 'cherry', 'date', 'elderberry']
. - We use the
reversed
function to reverse the order of elements in the list. - The reversed list is stored in a variable named
reversedList
. - Finally, we print the reversed list to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry");
val reversedList = list.reversed();
println(reversedList);
}
Output
[elderberry, date, cherry, banana, apple]
Summary
In this Kotlin tutorial, we learned about reversed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.