Kotlin, a modern programming language for Android development and more, provides robust and easy-to-use tools for handling collections. One of the most common operations performed on collections is sorting. Kotlin comes with built-in methods that make sorting a breeze.
Understanding Kotlin Collections
Before diving into the sorting methods, it is important to understand how Kotlin handles collections. The two main types of collections in Kotlin are:
- Mutable Collections: Collections that can be modified after their creation.
- Immutable Collections: Collections that cannot be changed after they are created.
Sorting: Destructively and Non-Destructively
In Kotlin, you can sort collections both destructively and non-destructively.
- Destructive sorting: Sorts the collection in-place and alters the original collection.
- Non-destructive sorting: Returns a new collection with sorted elements, leaving the original collection unchanged.
Built-in Sorting Methods
Kotlin provides several built-in methods for sorting, depending on whether you want destructive or non-destructive sorting and if you are sorting by natural order or providing a custom comparator.
Natural Order Sorting
For sorting of elements based on natural order, Kotlin has the following methods:
sort()
This is a destructive sorting method that sorts a mutable collection.
val mutableNumbers = mutableListOf(5, 3, 1, 4, 2)
mutableNumbers.sort()
println(mutableNumbers) // Output: [1, 2, 3, 4, 5]
sorted()
This is a non-destructive sorting method, returning a new list with elements sorted.
val numbers = listOf(5, 3, 1, 4, 2)
val sortedNumbers = numbers.sorted()
println(sortedNumbers) // Output: [1, 2, 3, 4, 5]
println(numbers) // Original list not altered, Output: [5, 3, 1, 4, 2]
Custom Comparator Sorting
For custom order sorting, you can use:
sortWith()
This is a destructive method for sorting using a custom comparator.
val mutableWords = mutableListOf("banana", "apple", "cherry")
mutableWords.sortWith(compareBy { it.length })
println(mutableWords) // Output: [apple, banana, cherry]
sortedWith()
This is a non-destructive sorting method for creating a new list using a custom comparator.
val words = listOf("banana", "apple", "cherry")
val sortedByLength = words.sortedWith(compareBy { it.length })
println(sortedByLength) // Output: [apple, banana, cherry]
Reverse Order Sorting
sortedDescending()
Used to sort elements in descending order in a non-destructive manner.
val descendingNumbers = numbers.sortedDescending()
println(descendingNumbers) // Output: [5, 4, 3, 2, 1]
sortDescending()
Sorts the collection in descending order destructively.
mutableNumbers.sortDescending()
println(mutableNumbers) // Output: [5, 4, 3, 2, 1]
Conclusion
Kotlin’s built-in methods for sorting collections provide a flexible framework for managing data both destructively and non-destructively. Whether you need a simple sort or one based on a particular parameter, Kotlin’s standard library has you covered.