This tutorial will teach you how to use the various sorting techniques available in Kotlin to arrange an array in both sending and desending order, along with examples.
Sorting is an essential function that enables data to be placed in a certain order. Kotlin has a variety of methods for sorting arrays, whether you want to arrange strings alphabetically or numbers in ascending order. This blog post will demonstrate how to use both custom sorting mechanisms and built-in functions to sort arrays in Kotlin.
What is an Array in Kotlin?
In Kotlin, an array is a collection of elements, where each element is identified by an index. An array is a fixed-size data structure, meaning its size cannot be changed once it’s initialized. Kotlin arrays are quite powerful, and they offer a wide range of methods to manipulate the data they hold. Sorting is one of the most frequently used operations.
Here’s a simple way to define an array in Kotlin:
val numbers = arrayOf(5, 2, 9, 1, 5, 6)
The array numbers
contains integer elements, but Kotlin supports arrays of any type, such as strings, characters, and floating-point numbers.
Why Sort an Array?
Sorting helps organize data in a meaningful way, making it easier to search, display, or process. For instance:
- Alphabetical sorting of names.
- Sorting a list of dates.
- Sorting numerical data for analysis.
Types of Sorting in Kotlin
There are primarily two types of sorting:
- Ascending Order: Sorting from the smallest to the largest.
- Descending Order: Sorting from the largest to the smallest.
Sorting Using Built-in Functions
Kotlin provides a rich set of built-in functions to handle sorting. Here are the most commonly used functions for sorting arrays in Kotlin:
1. sort()
Function
The sort()
function sorts the array in-place in ascending order. This means that it modifies the original array without creating a new one.
val numbers = arrayOf(5, 2, 9, 1, 5, 6)
numbers.sort()
println(numbers.joinToString()) // Output: 1, 2, 5, 5, 6, 9
2. sortDescending()
Function
The sortDescending()
function sorts the array in-place in descending order.
val numbers = arrayOf(5, 2, 9, 1, 5, 6)
numbers.sortDescending()
println(numbers.joinToString()) // Output: 9, 6, 5, 5, 2, 1
3. sortedArray()
Function
If you want to sort an array without modifying the original one, you can use sortedArray()
. It returns a new sorted array.
val numbers = arrayOf(5, 2, 9, 1, 5, 6)
val sortedNumbers = numbers.sortedArray()
println(sortedNumbers.joinToString()) // Output: 1, 2, 5, 5, 6, 9
4. sortedArrayDescending()
Function
Similarly, sortedArrayDescending()
returns a new array sorted in descending order.
val numbers = arrayOf(5, 2, 9, 1, 5, 6)
val sortedNumbers = numbers.sortedArrayDescending()
println(sortedNumbers.joinToString()) // Output: 9, 6, 5, 5, 2, 1
Sorting Custom Data Types
Kotlin allows sorting of custom objects by specifying how the comparison should be made. Let’s say you have a list of Person
objects, and you want to sort them by age.
data class Person(val name: String, val age: Int)
val people = arrayOf(
Person("John", 30),
Person("Alice", 22),
Person("Bob", 25)
)
To sort this list by age in ascending order:
people.sortBy { it.age }
println(people.joinToString { "${it.name}: ${it.age}" }) // Output: Alice: 22, Bob: 25, John: 30
To sort in descending order:
people.sortByDescending { it.age }
println(people.joinToString { "${it.name}: ${it.age}" }) // Output: John: 30, Bob: 25, Alice: 22
Sorting Strings in Kotlin
Sorting arrays of strings in Kotlin is straightforward using the same functions.
val fruits = arrayOf("Banana", "Apple", "Orange", "Mango", "Grapes")
fruits.sort()
println(fruits.joinToString()) // Output: Apple, Banana, Grapes, Mango, Orange
To sort in descending order:
fruits.sortDescending()
println(fruits.joinToString()) // Output: Orange, Mango, Grapes, Banana, Apple
Custom Sorting Using Comparator
Sometimes, you may want to sort data in a non-traditional way. For example, sorting strings by their length. In such cases, you can use Comparator
.
val fruits = arrayOf("Banana", "Apple", "Orange", "Mango", "Grapes")
fruits.sortWith(compareBy { it.length })
println(fruits.joinToString()) // Output: Apple, Mango, Banana, Orange, Grapes
Here, compareBy
allows us to sort strings by their length.
Sorting with sortedWith()
The sortedWith()
function is useful when you want to use a custom comparator without modifying the original array.
val fruits = arrayOf("Banana", "Apple", "Orange", "Mango", "Grapes")
val sortedFruits = fruits.sortedWith(compareByDescending { it.length })
println(sortedFruits.joinToString()) // Output: Orange, Banana, Grapes, Apple, Mango
Sorting Numbers with sortedBy
and sortedByDescending
sortedBy
and sortedByDescending
are also handy for sorting by a specific property or condition. They return a new list instead of modifying the original array.
val numbers = arrayOf(5, 12, 9, 1, 25, 6)
val sortedNumbers = numbers.sortedBy { it % 10 }
println(sortedNumbers.joinToString()) // Output: 1, 12, 5, 25, 6, 9
Sorting Mutable Lists
If you are working with MutableList
instead of arrays, the same sorting functions apply:
val numbers = mutableListOf(5, 2, 9, 1, 5, 6)
numbers.sort()
println(numbers) // Output: [1, 2, 5, 5, 6, 9]
Summary of Sorting Functions
Function | Description |
---|---|
sort() | Sorts the array in-place in ascending order. |
sortDescending() | Sorts the array in-place in descending order. |
sortedArray() | Returns a new array sorted in ascending order. |
sortedArrayDescending() | Returns a new array sorted in descending order. |
sortBy { … } | Sorts by a specific property in ascending order. |
sortByDescending { … } | Sorts by a specific property in descending order. |
sortedWith(comparator) | Sorts with a custom comparator. |
sortWith(comparator) | Sorts the array in-place with a custom comparator. |
Conclusion
Sorting arrays in Kotlin is straightforward thanks to its extensive standard library functions. Whether you need simple sorting, custom sorting, or sorting complex objects, Kotlin provides a solution. Leveraging built-in functions like sort()
, sortedArray()
, sortBy()
, and Comparator
, you can handle a variety of sorting scenarios with ease.
Sorting is not only about ordering data; it’s about making data meaningful, accessible, and usable for various computational tasks. Kotlin’s clear and concise syntax makes sorting operations efficient and enjoyable.