Kotlin Array.sort() function
In Kotlin, the Array.sort()
function is used to sort the elements of an array in ascending order. This function modifies the original array in-place, resulting in a new order of elements.
This can be useful when you want to organize the elements of an array in a specific order, such as arranging a list of numbers, strings, or custom objects in ascending order.
In this tutorial, we’ll explore the syntax of the sort()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the Array.sort()
function is:
fun <T : Comparable<T>> Array<out T>.sort()
The sort()
function is an extension function specifically designed for arrays of elements that implement the Comparable
interface. It modifies the original array in-place.
Examples for Array.sort() function
1. Sorting an Array of Numbers
In this example, we’ll use sort()
to sort the elements of an array of numbers numbersArray
in ascending order.
Kotlin Program
fun main() {
val numbersArray = intArrayOf(5, 2, 8, 1, 7)
println("Original Array\n${numbersArray.contentToString()}")
// Sorting the array of numbers
numbersArray.sort()
// Printing the sorted array
println("Sorted Array\n${numbersArray.contentToString()}")
}
Output
Original Array
[5, 2, 8, 1, 7]
Sorted Array
[1, 2, 5, 7, 8]
2. Sorting an Array of Strings
In this example, we’ll use sort()
to sort the elements of an array of strings in lexicographical order.
Kotlin Program
fun main() {
val wordsArray = arrayOf("banana", "kiwi", "apple", "mango")
println("Original Array\n${wordsArray.contentToString()}")
// Sorting the array of strings
wordsArray.sort()
// Printing the sorted array
println("Sorted Array\n${wordsArray.contentToString()}")
}
Output
Original Array
[banana, kiwi, apple, mango]
Sorted Array
[apple, banana, kiwi, mango]
Summary
In this tutorial, we’ve covered the Array.sort()
function in Kotlin, its syntax, and how to use it to sort the elements of an array in ascending order.