如何使用Kotlin中的多个比较字段按降序排序

Aug*_*rmo 17 kotlin

Kotlin允许我使用多个比较字段对ASC和数组进行排序.

例如:

return ArrayList(originalItems)
    .sortedWith(compareBy({ it.localHits }, { it.title }))
Run Code Online (Sandbox Code Playgroud)

但是当我尝试排序DESC(compareByDescending())时,它不允许我使用多个比较字段.

有什么办法可以吗?

ear*_*jim 32

您可以使用thenByDescending()(或thenBy()升序)扩展功能来定义辅助Comparator.

假设originalItemsSomeCustomObject,这样的东西应该工作:

return ArrayList(originalItems)
        .sortedWith(compareByDescending<SomeCustomObject> { it.localHits }
                .thenByDescending { it.title })
Run Code Online (Sandbox Code Playgroud)

(当然你必须SomeCustomObject用你自己的通用类型替换)


leo*_*mer 8

您也可以只使用 sort ASC 然后将其反转:

return ArrayList(originalItems).sortedWith(compareBy({ it.localHits }, { it.title })).asReversed()
Run Code Online (Sandbox Code Playgroud)

的实现asReversed()是带有反向索引的排序列表的视图,比使用具有更好的性能reverse()


Jav*_*rSA 6

ArrayList(originalItems)
    .sortedWith(compareByDescending({ it.localHits }, { it.title }))
Run Code Online (Sandbox Code Playgroud)

你只需要定义这个函数:

fun <T> compareByDescending(vararg selectors: (T) -> Comparable<*>?): Comparator<T> {
    return Comparator { b, a -> compareValuesBy(a, b, *selectors) }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以直接使用Comparator

ArrayList(originalItems)
    .sortedWith(Comparator { b, a -> compareValuesBy(a, b, { it.localHits }, { it.title }) })
Run Code Online (Sandbox Code Playgroud)