To sort a list in ascending order in Kotlin, you can use the sort()
method or the sorted()
method of the List class.
In this example,
numbers
with integer values.sort()
method on the numbers
list to sort it in ascending order.sort()
method sorts the elements in place, modifying the original list.fun main() {
val numbers = mutableListOf(5, 2, 8, 1, 3)
numbers.sort()
println("Sorted list in ascending order: $numbers")
}
Sorted list in ascending order: [1, 2, 3, 5, 8]
In this example,
words
with string values.sort()
method on the words
list to sort it in ascending order.sort()
method sorts the elements in place, modifying the original list.fun main() {
val words = mutableListOf("banana", "apple", "cherry")
words.sort()
println("Sorted list in ascending order: $words")
}
Sorted list in ascending order: [apple, banana, cherry]
In this tutorial, we learned How to Sort a List in Ascending Order in Kotlin language with well detailed examples.