如何在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
- Define Type Order: First, set a priority for each
Itemsubclass to determine their overall order in the sorted list. You can do this directly in the comparator using awhenexpression. - Sort by Type-Specific Properties: For items of the same type, sort them using their unique properties (like
idfor Server,datefor 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
whenexpression. For example, if you want Footer to come first, setis Footer -> 0,is Server ->1, etc. - Descending Sort for Properties: Use
thenByDescendinginstead ofthenByif 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
thenBycalls:.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
相关产品推荐
相关产品推荐

