Kotlin List Sort Example - Ascending and Descending Order

This example shows how to sort List values in Kotlin. Since the lists created with listOf() are read-only, the methods do not alter the list but return a new modified list.

Kotlin List Sort Example - Ascending and Descending Order

The example sorts list values in ascending and descending order, reverses list elements.
package net.sourcecodeexamples.kotlin

fun main() {

 val nums = listOf(10, 5, 3, 4, 2, 1, 11, 14, 12)

 val sortAsc = nums.sorted()
 println("sortAsc -> " + sortAsc)

 val sortDesc = nums.sortedDescending()
 println("sortDesc -> " + sortDesc)

 val revNums = nums.reversed()
 println("revNums -> " + revNums)
}
Output:
sortAsc -> [1, 2, 3, 4, 5, 10, 11, 12, 14]
sortDesc -> [14, 12, 11, 10, 5, 4, 3, 2, 1]
revNums -> [12, 14, 11, 1, 2, 4, 3, 5, 10]

Comments