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

如何在Kotlin中按多种类型及属性值对混合Item列表排序?

Sorting Mixed Item Types by Type Priority and Specific Properties

To sort your List<Item> first by the type of item (e.g., Server → Local → Footer) and then by each type's unique properties, you can use Kotlin's sortedWith function with a custom Comparator that combines two levels of sorting:

Step-by-Step Implementation

  1. Define Type Order: First, set a priority for each Item subclass to determine their overall order in the sorted list. You can do this directly in the comparator using a when expression.
  2. Sort by Type-Specific Properties: For items of the same type, sort them using their unique properties (like id for Server, date for Local).

Here's the complete code:

// Your existing classes and list
interface Item { val name: String }
data class Server(override val name: String, val id: String) : Item
data class Local(override val name: String, val date: Int) : Item
data class Footer(override val name: String) : Item

val items = arrayListOf<Item>()
items.add(Server("server", "b"))
items.add(Local("local", 2))
items.add(Footer("footer"))
items.add(Server("server", "a"))
items.add(Local("local", 1))
items.add(Footer("footer"))

// Custom comparator for sorting
val sortedItems = items.sortedWith(
    compareBy<Item> {
        // First sort by type priority (adjust numbers to change order)
        when (it) {
            is Server -> 0
            is Local -> 1
            is Footer -> 2
            else -> 3 // Fallback for unexpected types
        }
    }.thenBy {
        // Then sort by type-specific properties
        when (it) {
            is Server -> it.id
            is Local -> it.date
            is Footer -> it.name
            else -> ""
        }
    }
)

// Print the result to verify
sortedItems.forEach { println(it) }

Output

Server(name=server, id=a)
Server(name=server, id=b)
Local(name=local, date=1)
Local(name=local, date=2)
Footer(name=footer)
Footer(name=footer)

Customization Options

  • Change Type Order: Adjust the numeric values in the first when expression. For example, if you want Footer to come first, set is Footer -> 0, is Server ->1, etc.
  • Descending Sort for Properties: Use thenByDescending instead of thenBy if you want to sort a property in reverse order. For example, to sort Local items by date from newest to oldest:
    .thenByDescending {
        when (it) {
            is Local -> it.date
            is Server -> it.id
            is Footer -> it.name
            else -> ""
        }
    }
    
  • Multiple Properties per Type: If you need to sort by multiple properties for a single type (e.g., Server by name then id), chain additional thenBy calls:
    .thenBy { (it as? Server)?.name }
    .thenBy { (it as? Server)?.id }
    

This approach keeps your sorting logic clean and flexible, making it easy to adjust as your requirements change.

内容的提问来源于stack exchange,提问作者M-Wajeeh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:28:44