如何根据Kotlin中的多种类型和值进行排序?

时间:2018-03-24 02:49:16

标签: sorting kotlin comparator comparable

给出以下课程:

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

1 个答案:

答案 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
    }
}))

我们在这里做什么:

  1. 我们正在为Item的实现创建syntetic比较器。当然,如果这个常用用例,这个数字可能只是界面中的另一个字段。
  2. 我们在ServerLocal上定义要比较的字段,因为它们有额外的排序标准。
  3. 我们将步骤1和2中创建的比较器传递给compareBy功能。
  4. 此操作后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