To sort a list in Kotlin, you can use the sorted
method for ascending order and the sortedDescending
method for descending order. These methods are part of the Kotlin Collections library.
In this example,
numbers
with integer values.sorted
method to sort the list in ascending order and store the sorted list in the variable sortedNumbers
.sorted
method sorts the elements in natural order.fun main() {
val numbers = listOf(5, 2, 8, 1, 3)
val sortedNumbers = numbers.sorted()
println("Sorted list in ascending order: $sortedNumbers")
}
Sorted list in ascending order: [1, 2, 3, 5, 8]
In this example,
numbers
with integer values.sortedDescending
method to sort the list in descending order and store the sorted list in the variable sortedNumbers
.sortedDescending
method sorts the elements in reverse natural order.fun main() {
val numbers = listOf(5, 2, 8, 1, 3)
val sortedNumbers = numbers.sortedDescending()
println("Sorted list in descending order: $sortedNumbers")
}
Sorted list in descending order: [8, 5, 3, 2, 1]
In this tutorial, we learned How to Sort a List in Kotlin language with well detailed examples.