How to Sort List in Kotlin: Simple Syntax and Examples
In Kotlin, you can sort a list using the
sorted() function to get a new sorted list or sort() to sort a mutable list in place. You can also use sortedBy or sortedWith for custom sorting rules.Syntax
Kotlin provides several ways to sort lists:
list.sorted(): Returns a new list sorted in ascending order.mutableList.sort(): Sorts the mutable list in place.list.sortedBy { selector }: Sorts by a specific property or value.list.sortedWith(comparator): Sorts using a custom comparator.
kotlin
val list = listOf(3, 1, 4, 2) val sortedList = list.sorted() // returns new sorted list val mutableList = mutableListOf(3, 1, 4, 2) mutableList.sort() // sorts in place val sortedByLength = listOf("apple", "kiwi", "banana").sortedBy { it.length } val sortedWithComparator = listOf("apple", "kiwi", "banana").sortedWith(compareBy { it.length })
Example
This example shows how to sort a list of numbers and a list of strings by length.
kotlin
fun main() {
val numbers = listOf(5, 3, 8, 1)
val sortedNumbers = numbers.sorted()
println("Sorted numbers: $sortedNumbers")
val fruits = listOf("pear", "apple", "banana", "kiwi")
val sortedFruitsByLength = fruits.sortedBy { it.length }
println("Fruits sorted by length: $sortedFruitsByLength")
val mutableNumbers = mutableListOf(10, 2, 7, 4)
mutableNumbers.sort()
println("Mutable numbers sorted in place: $mutableNumbers")
}Output
Sorted numbers: [1, 3, 5, 8]
Fruits sorted by length: [pear, kiwi, apple, banana]
Mutable numbers sorted in place: [2, 4, 7, 10]
Common Pitfalls
One common mistake is trying to use sort() on an immutable list, which causes a compile error because sort() modifies the list in place and only works on mutable lists. Another is expecting sorted() to change the original list, but it returns a new sorted list instead.
kotlin
fun main() {
val immutableList = listOf(3, 2, 1)
// immutableList.sort() // Error: Unresolved reference: sort
val sortedList = immutableList.sorted() // Correct: returns new sorted list
println("Original list: $immutableList")
println("Sorted list: $sortedList")
}Output
Original list: [3, 2, 1]
Sorted list: [1, 2, 3]
Quick Reference
Here is a quick summary of Kotlin list sorting functions:
| Function | Description |
|---|---|
list.sorted() | Returns a new list sorted in ascending order. |
mutableList.sort() | Sorts the mutable list in place. |
list.sortedBy { selector } | Sorts by a property or value. |
list.sortedWith(comparator) | Sorts using a custom comparator. |
Key Takeaways
Use
sorted() to get a new sorted list without changing the original.Use
sort() only on mutable lists to sort them in place.Use
sortedBy or sortedWith for custom sorting rules.Immutable lists cannot be sorted in place; always use
sorted() for them.Remember that
sorted() returns a new list and does not modify the original.