给出以下课程:
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"))
items.add(Server("server", "c"))
items.add(Local("local", 0))
并对其进行排序:
val groupBy = items.groupBy { it.name }
val partialSort = arrayListOf<Item>()
//individually sort each type
partialSort.addAll(groupBy["local"]!!.map { it as Local }.sortedWith(compareBy({ it.date })))
partialSort.addAll(groupBy["server"]!!.map { it as Server }.sortedWith(compareBy({ it.id })))
partialSort.addAll(groupBy["footer"]!!.map { it as Footer })
//this can be avoided if above three lines are rearranged
val fullSort = partialSort.sortedWith(compareBy({ it is Footer }, { it is Local }, { it is Server }))
然后我得到一个列表,如果它是由以下注释代码创建的:
// items.add(Server("server", "a"))
// items.add(Server("server", "b"))
// items.add(Server("server", "c"))
// items.add(Local("local", 0))
// items.add(Local("local", 1))
// items.add(Local("local", 2))
// items.add(Footer("footer"))
// items.add(Footer("footer"))
有没有更好的方式对它进行排序? 我看过How to sort based on/compare multiple values in Kotlin? 和Sort collection by multiple fields in Kotlin已经但不能将其应用于我的代码。
答案 0 :(得分:3)
是的,它可以通过单一操作实现(但非常复杂)并且您正在以正确的方式思考,compareBy
可以为您做到这一点
items.sortWith(compareBy({
when (it) {
is Server -> -1
is Local -> 0
is Footer -> 1
else -> Integer.MAX_VALUE
}
}, {
when (it) {
is Server -> it.id
is Local -> it.date
else -> 0
}
}))
我们在这里做什么:
Server
和Local
上定义要比较的字段,因为它们有额外的排序标准。 compareBy
功能。此操作后items
个集合已排序:
[Server(name=server, id=a), Server(name=server, id=b), Server(name=server, id=c), Local(name=local, date=0), Local(name=local, date=1), Local(name=local, date=2), Footer(name=footer), Footer(name=footer)]
UPD :如果Item
的名称也要排序 - 您可以在适当的位置轻松添加一个比较Item::name
。