Kotlin中实现多重排序

218 阅读1分钟

A:

Kotlin存在如下数据类

data class A(val f: Int, val h:Int, val g:Int) 

List<A>进行排序,要求先按f升序排列,当f相同时按h升序排列,当h相同时按g升序排列如何实现?

Q:

在 Kotlin 中,可以使用sortedWith函数结合 compareBy 来实现对 List<A> 的多重条件排序。

data class A(val f: Int, val h: Int, val g: Int)

fun main() {
    val list = listOf(
        A(1, 2, 3),
        A(1, 1, 2),
        A(2, 3, 1),
        A(1, 2, 1)
    )

    val sortedList = list.sortedWith(compareBy({ it.f }, { it.h }, { it.g }))

    println(sortedList)
}

compareBy 函数接受多个选择器函数(也称为键选择器),这些函数按照提供的顺序依次用于比较元素。因此,它首先按 f 排序,如果 f 相同,再按 h 排序,最后按 g 排序。这样就实现了问题所描述的排序逻辑。