Sorting an Array of Strings in Kotlin: A Complete Guide

Programming requires sorting, and Kotlin offers a number of techniques for effectively sorting arrays. When working with jobs like organising names, words, or text data, sorting an array of strings is a frequent practice. This thorough tutorial will cover sorting arrays of strings in Kotlin using custom comparators, built-in functions, and sophisticated sorting strategies. If you need anything learning based on then you can also check Sorting an array of Integer value in Kotlin. It will be helpful for that.

1. Understanding Arrays in Kotlin

An array in Kotlin is a fixed-size collection of elements of a specified type. Arrays of strings (Array<String>) store multiple strings in a single variable.

Creating an Array of Strings

You can create a string array using the arrayOf function.

val words = arrayOf("banana", "apple", "cherry", "date", "elderberry")

Here, words is an Array<String> containing a list of fruit names.


2. Sorting Using Built-in Functions

Kotlin’s standard library provides built-in functions to sort arrays easily.

a) sorted() and sortedDescending() Functions

  • sorted() returns a list sorted in ascending (lexicographical) order.
  • sortedDescending() returns a list sorted in descending order.

Example:

val words = arrayOf("banana", "apple", "cherry", "date", "elderberry")

val sortedAsc = words.sorted()
val sortedDesc = words.sortedDescending()

println("Ascending: $sortedAsc")        // Output: [apple, banana, cherry, date, elderberry]
println("Descending: $sortedDesc")      // Output: [elderberry, date, cherry, banana, apple]

b) sort() Function

To sort an array in place, use the sort() method.

Example:

val words = arrayOf("banana", "apple", "cherry", "date", "elderberry")

words.sort()  // Sorts in ascending order
println(words.joinToString())  // Output: apple, banana, cherry, date, elderberry

For descending order:

words.sortDescending()
println(words.joinToString())  // Output: elderberry, date, cherry, banana, apple

3. Custom Sorting with Comparators

Kotlin allows custom sorting using the sortWith() function and comparators.

a) Sorting by String Length

You can sort strings based on their length using a custom comparator.

Example:

val words = arrayOf("banana", "apple", "cherry", "date", "elderberry")

words.sortWith(compareBy { it.length })
println(words.joinToString())  // Output: date, apple, banana, cherry, elderberry

b) Sorting in Reverse by Length

To sort in reverse order by length, use compareByDescending.

words.sortWith(compareByDescending { it.length })
println(words.joinToString())  // Output: elderberry, banana, cherry, apple, date

c) Case-insensitive Sorting

By default, Kotlin sorts strings with case sensitivity. To perform case-insensitive sorting, use compareBy.

Example:

val words = arrayOf("Banana", "apple", "Cherry", "date", "Elderberry")

words.sortWith(compareBy { it.lowercase() })
println(words.joinToString())  // Output: apple, Banana, Cherry, date, Elderberry

4. Sorting Using Lambdas

Kotlin’s support for lambda expressions enables concise custom sorting.

Example: Sort by Last Character

val words = arrayOf("banana", "apple", "cherry", "date", "elderberry")

words.sortWith { a, b -> a.last().compareTo(b.last()) }
println(words.joinToString())  // Output: banana, apple, date, cherry, elderberry

5. Sorting with Multiple Conditions

You can sort using multiple criteria by chaining comparators.

Example: Sort by Length, then Alphabetically

val words = arrayOf("banana", "apple", "cherry", "date", "elderberry")

words.sortWith(compareBy<String> { it.length }.thenBy { it })
println(words.joinToString())  // Output: date, apple, banana, cherry, elderberry

6. Mutable vs Immutable Sorting

  • Mutable Arrays: sort() sorts in place.
  • Immutable Arrays: sorted() returns a new list.

Mutable Example:

val mutableArray = arrayOf("banana", "apple", "cherry")

mutableArray.sort()
println(mutableArray.joinToString())  // Output: apple, banana, cherry

Immutable Example:

val immutableArray = listOf("banana", "apple", "cherry")

val sortedList = immutableArray.sorted()
println(sortedList)  // Output: [apple, banana, cherry]

7. Sorting in Natural and Reverse Order

Kotlin provides sortedBy and sortedByDescending for sorting by a custom selector.

Example: Natural Order by Length

val words = arrayOf("banana", "apple", "cherry")

val sortedByLength = words.sortedBy { it.length }
println(sortedByLength)  // Output: [apple, banana, cherry]

Example: Reverse Order by Length

val sortedByLengthDesc = words.sortedByDescending { it.length }
println(sortedByLengthDesc)  // Output: [banana, cherry, apple]

8. Sorting in Different Locales

Kotlin’s Collator class allows sorting based on locale-specific rules.

Example: Locale-based Sorting

import java.text.Collator
import java.util.Locale

val words = arrayOf("äpfel", "apfel", "banana", "Apfel")

val collator = Collator.getInstance(Locale.GERMANY)
words.sortWith(collator)
println(words.joinToString())  // Locale-specific sorting

9. Sorting with Null Values

Kotlin can handle null values in arrays while sorting.

Example: Sort with Nulls First

val words = arrayOf("banana", null, "apple", "cherry")

words.sortWith(compareBy(nullsFirst()) { it })
println(words.joinToString())  // Output: null, apple, banana, cherry

10. Conclusion

Sorting an array of strings in Kotlin is simple yet flexible, thanks to Kotlin’s built-in functions and lambda capabilities. Whether you’re sorting alphabetically, by length, or using custom logic, Kotlin provides an elegant and concise syntax to achieve it. Mastering these sorting techniques will enhance your ability to manage textual data effectively.