Kotlin Set Sort Example - Ascending and Descending Order

This post shows how to sort Set values in Kotlin. Since the sets created with setOf() are read-only, the methods do not alter the set but return a new modified list.

Kotlin Set Sort Example - Ascending and Descending Order

The example sorts set of values in ascending and descending order and reverse list elements.
package net.sourcecodeexamples.kotlin

fun main() {

 val nums = setOf(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