You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin中使用多比较字段实现降序排序?

Kotlin多字段降序排序的解决方法

Great question! You absolutely can sort collections by multiple fields in descending order in Kotlin—you just need to leverage the chaining capabilities of Kotlin's comparator builders. Let's break down the two most straightforward approaches:

方法1:使用compareByDescending() + thenByDescending()

The compareByDescending() function returns a Comparator that you can extend with additional sorting rules using thenByDescending() (for subsequent descending fields) or thenBy() (if you need a mix of descending and ascending).

Here's how to adapt your original code for full descending multi-field sorting:

// 假设你的数据类是这样的(根据实际情况替换)
data class Item(val localHits: Int, val title: String)

fun sortItemsDescending(originalItems: List<Item>): List<Item> {
    return ArrayList(originalItems).sortedWith(
        compareByDescending<Item> { it.localHits }
            .thenByDescending { it.title }
    )
}

工作原理:

  • First, the list is sorted in descending order by localHits (highest values first).
  • When two items have the same localHits value, they're further sorted in descending order by title (alphabetically reverse order, e.g., "Cherry" comes before "Banana").

方法2:使用compareBy() + 反转比较器

If you prefer a more unified syntax, you can use compareBy() with reverseOrder() for each field you want to sort descending. This is especially useful if you need to mix ascending and descending rules in the same sort:

fun sortItemsDescending(originalItems: List<Item>): List<Item> {
    return ArrayList(originalItems).sortedWith(
        compareBy(
            reverseOrder<Int>(), { it.localHits }, // 按localHits降序
            reverseOrder<String>(), { it.title }   // 按title降序
        )
    )
}

混合排序示例(可选):

If you wanted to sort localHits descending but title ascending, you'd just omit the reverseOrder() for the title field:

compareBy(
    reverseOrder<Int>(), { it.localHits },
    { it.title } // 按title升序
)

为什么你之前觉得不能用多字段?

The confusion often comes from thinking compareByDescending() only accepts a single selector—but it actually returns a flexible Comparator instance that supports chaining with thenByDescending()/thenBy() to add as many additional sorting criteria as you need.

内容的提问来源于stack exchange,提问作者Augusto Carmo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:34:59