Sling Academy
Home/Kotlin/Sorting Collections in Kotlin: Built-in Methods

Sorting Collections in Kotlin: Built-in Methods

Last updated: November 30, 2024

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.

Next Article: Transforming Collections with `map`, `flatMap`, and `mapNotNull` in Kotlin

Previous Article: Converting Between Arrays, Lists, Sets, and Maps in Kotlin

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin