Kotlin Program to Sort Elements in Lexicographical Order (Dictionary Order)

Sorting elements in lexicographical order, also known as dictionary order, is a common task in programming. Kotlin provides various ways to achieve this sorting based on different criteria. In this article, we’ll explore three different Kotlin Program to Sort Elements in Lexicographical Order (Dictionary Order).

1. Example 1: Sort Strings in Lexicographical Order

This example demonstrates how to sort an array of strings in lexicographical order using Kotlin’s built-in sorting function.

Kotlin
import java.util.Arrays

fun main() {
    val words = arrayOf("apple", "banana", "cherry", "date", "grape")
    Arrays.sort(words)
    println("Sorted words:")
    for (word in words) {
        println(word)
    }
}

Output

Kotlin
Sorted words:
apple
banana
cherry
date
grape

2. Example 2: Sort Integers in Lexicographical Order

In this example, we sort an array of integers in lexicographical order by converting them to strings and using the sortedWith function with a custom comparator.

Code

Kotlin
fun main() {
    val numbers = arrayOf(25, 10, 100, 5, 50)
    val sortedNumbers = numbers.sortedWith(compareBy { it.toString() })
    println("Sorted numbers:")
    println(sortedNumbers.joinToString())
}

Output

Kotlin
Sorted numbers:
10, 100, 25, 5, 50

3. Example 3: Sort Custom Objects in Lexicographical Order

Here, we sort a list of custom objects in lexicographical order based on a specific property using the sortedBy function.

Code

Kotlin
data class Person(val name: String, val age: Int)

fun main() {
    val people = listOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
    val sortedPeople = people.sortedBy { it.name }
    println("Sorted people:")
    for (person in sortedPeople) {
        println("${person.name} - ${person.age}")
    }
}

Output

Kotlin
Sorted people:
Alice - 30
Bob - 25
Charlie - 35

4. Conclusion

Sorting elements in lexicographical order is a fundamental operation in programming, and Kotlin offers various methods to accomplish this task efficiently. Whether sorting strings, integers, or custom objects, understanding these different approaches enhances your Kotlin programming skills and prepares you for handling diverse sorting requirements in your applications