Sorting By Functions in Kotlin

Our example demonstrates how to sort collections using custom comparison functions in Kotlin. Here’s the full source code:

import kotlin.comparisons.compareBy

fun main() {
    val fruits = mutableListOf("peach", "banana", "kiwi")

    // We implement a comparison function for string lengths.
    val lenCmp = compareBy<String> { it.length }

    // Now we can call sortWith with this custom comparison function
    // to sort `fruits` by name length.
    fruits.sortWith(lenCmp)
    println(fruits)

    // We can use the same technique to sort a list of
    // values that aren't built-in types.
    data class Person(val name: String, val age: Int)

    val people = mutableListOf(
        Person("Jax", 37),
        Person("TJ", 25),
        Person("Alex", 72)
    )

    // Sort `people` by age using sortWith.
    // Note: if the Person class is large,
    // you may want to use a list of Person references instead
    // and adjust the sorting function accordingly. If in
    // doubt, benchmark!
    people.sortWith(compareBy { it.age })
    println(people)
}

This code demonstrates sorting collections using custom comparison functions in Kotlin. Let’s break it down:

  1. We start with a list of fruits and create a custom comparison function lenCmp using compareBy to compare strings by their length.

  2. We use sortWith to sort the fruits list using our custom comparison function.

  3. We then define a Person data class with name and age properties.

  4. We create a list of Person objects and sort it by age using sortWith and compareBy.

  5. Finally, we print both sorted lists.

To run the program, save it as SortingByFunctions.kt and use the Kotlin compiler:

$ kotlinc SortingByFunctions.kt -include-runtime -d SortingByFunctions.jar
$ java -jar SortingByFunctions.jar
[kiwi, peach, banana]
[Person(name=TJ, age=25), Person(name=Jax, age=37), Person(name=Alex, age=72)]

This example showcases Kotlin’s powerful sorting capabilities using lambdas and the standard library functions sortWith and compareBy. These methods provide a concise and flexible way to implement custom sorting logic for both built-in and user-defined types.