Kotlin sortedWith syntax and lambda examples

As a quick note, here’s an example of how to use the Kotlin sortedWith syntax with an anonymous function (lambda). Given this list of integers:

val list = listOf(7,3,5,9,1,3)

Here’s an example of how to use sortedWith using a Comparator and lambda:

list.sortedWith(Comparator<Int>{ a, b ->
    when {
        a > b -> 1
        a < b -> -1
        else -> 0
    }
})

When you run that code you’ll see this output:

[1, 3, 3, 5, 7, 9]

As shown in the example, the key to the solution is knowing how to write a comparator in Kotlin. Similar to Java, a comparator is a function that returns 1, -1, and 0 depending on how the two variables that are passed to the function — technically an anonymous function, or lambda — compare to each other.

Kotlin sortedWith and a list of strings

Similarly, this is how you sort a list of strings alphabetically in Kotlin using sortedWith:

val names = listOf("kim", "julia", "jim", "hala")

names.sortedWith(Comparator<String>{ a, b ->
    when {
        a > b -> 1
        a < b -> -1
        else -> 0
    }
})

The result of that expression is:

[hala, jim, julia, kim]

Likewise, this is how to sort a list of strings in Kotlin by the string length using sortedWith:

names.sortedWith(Comparator<String>{ a, b ->
    when {
        a.length > b.length -> 1
        a.length < b.length -> -1
        else -> 0
    }
})
[kim, jim, hala, julia]

In summary, I hope these Kotlin sortedWith examples are helpful.