【问题标题】:How to sort based on multiple types and values in Kotlin?如何在 Kotlin 中根据多种类型和值进行排序?
【发布时间】:2018-09-02 18:48:20
【问题描述】:

给定以下类:

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 已经但无法将其应用于我的代码。

【问题讨论】:

  • 是否假设子类类型和名称属性始终相同(不区分大小写)?
  • 我希望得到一个不假设的答案。但是可以肯定地说子类类型和名称属性总是相同的。
  • 我的回答有帮助吗?

标签: sorting kotlin comparator comparable


【解决方案1】:

是的,它可以在单个操作中实现(但非常复杂)并且您的想法是正确的,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
    }
}))

我们在这里做什么:

  1. 我们正在为项目的实现创建综合比较器。当然,如果这是常见的用例,这个数字可能只是界面中的另一个字段。
  2. 我们正在定义要在ServerLocal 上进行比较的字段,因为它们具有额外的排序标准。
  3. 我们将在第 1 步和第 2 步中创建的比较器传递给 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

【讨论】:

    猜你喜欢
    • 2011-10-21
    • 2011-12-09
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 2011-04-21
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多