How to sort a collection by multiple values AND nulls at the end using the available convenient methods of Kotlin

Gama the Great :

I've used the sortedWith and compareBy methods before and it is capable of sorting using multiple parameters.

I've also used nullsLast method before and it is quite convenient just like the other two.

With these methods, however, I can't figure out a way to sort a collection with the following sorting rules:

Given the Class:

data class MyClass(
    val varA: String?,
    val varB: String
)
  • sort according to varA alphabetically and nulls/blank to be last; then

  • sort according to varB alphabetically

So let's say I have the following collection:

val collection = listOf(
    MyClass(null, "A"),
    MyClass("a", "B"),
    MyClass("c", "C"),
    MyClass("b", "D"),
    MyClass("", "E"),
    MyClass("a", "F"),
    MyClass("b", "G"),
    MyClass(null, "H"),
    MyClass("", "I")
)

it should then be sorted to:

    MyClass("a", "B")
    MyClass("a", "F")
    MyClass("b", "D")
    MyClass("b", "G")
    MyClass("c", "C")
    MyClass(null, "A")
    MyClass("", "E")
    MyClass(null, "H")
    MyClass("", "I")

is there a one-liner code I can use just like the compareBy that uses vararg parameter

Alexey Romanov :

I would do it like this (see kotlin.comparisons documentation):

val comparator = compareBy<String, MyClass>(nullsLast(), { it.varA.let { if (it == "") null else it } }).thenBy { it.varB }

collection.sortedWith(comparator)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=32988&siteId=1