Kotlin 首先按空值对对象数组进行排序,然后降序

时间:2021-01-13 20:41:07

标签: arrays sorting kotlin

我想对 Kotlin 对象数组进行排序,首先使用空值,然后对值进行降序排序。 这与 Kotlin sorting nulls last 类似,但排序略有不同。

data class stuff(
    var value: String? = null, // null possible here
    var value2: String = "" 
) {
    fun debug(): String { return "\n $value: $value2" }
}

fun main() {
    val someArray = arrayOf(
        stuff(value="1", value2="1st non null"),
        stuff(value=null, value2="a null key"),
        stuff(value="3", value2="3rd non null"),
        stuff(value=null, value2="another null"),
        stuff(value="2", value2="2nd non null"),
    )
    println("unsorted array: ${someArray.map{ it.debug() }}")

    someArray.sortByDescending{it.value}
    println("\nsorted array: ${someArray.map{ it.debug() }}")

    someArray.sortWith(nullsLast(compareBy { it.value }))
    println("\nsorted array another way: ${someArray.map{ it.debug() }}")
}

当前输出:

unsorted array: [
 1: 1st non null, 
 null: a null key, 
 3: 3rd non null, 
 null: another null, 
 2: 2nd non null]

sorted array: [
 3: 3rd non null, 
 2: 2nd non null, 
 1: 1st non null, 
 null: a null key, 
 null: another null]

sorted array another way: [
 null: a null key, 
 null: another null, 
 1: 1st non null, 
 2: 2nd non null, 
 3: 3rd non null]

我希望它像这样排序(空顺序无关紧要,但其余顺序降序):

[
 null: a null key, 
 null: another null, 
 3: 3rd non null,
 2: 2nd non null,
 1: 1st non null]

我怎样才能有效地做到这一点?谢谢!

0 个答案:

没有答案