是否可以通过简单的方式对 groupBy 中的每个组进行排序?

Is it possible to sort each group in groupBy in a simple way?

我有一个功能可以将我的高分列表分组为每个类别,但是当我得到这些组时,它们不再按顺序排列并且得分最高的人被随机放置在列表中的某个位置。

我想知道是否有一种简单的方法可以对每个组进行排序。

我的分组函数如下所示:

private fun getCategories(scores: List<HighScore>): List<Pair<String, List<HighScore>>> {
    return scores.groupBy {
        it.word.category
    }.toList()
}

我的模型是这样的


data class HighScore(
    val ID: String?,
    val player: String,
    val time: Int,
    val hints: Int,
    val wrongs: Int,
    val word: Word
) {
    fun getScore():Int {
        return time*word.difficulty/hints/(wrongs+1)
    }
}

我的旧排序函数看起来像这样(但我想我可以只使用 sortedByDescending()

private fun order(scores: ArrayList<HighScore>): List<HighScore> {
    scores
        .sortWith(kotlin.Comparator { lhs, rhs ->
            when {
                lhs.getScore() > rhs.getScore() -> -1
                lhs.getScore() < rhs.getScore() -> 1
                else -> 0
            }
        })

    return if (scores.size > 10) {
        scores.slice(0 until 10)
    } else {
        scores
    }
}

提前致谢:-)

你可以将你的功能改进成这样:

    private fun getCategories(scores: List<HighScore>): List<Pair<String, List<HighScore>>> {
        return scores
            .sortedByDescending { it.getScore() }
            .groupBy { it.word.category }
            .mapValues { it.value.take(10) }
            .map { Pair(it.key, it.value) }
    }

如果您只使用 Map<String, List<HighScore>> 而不是 List<Pair<String, List<HighScore>>> 作为 return 类型,可能会更简单:

    private fun getCategories(scores: List<HighScore>): Map<String, List<HighScore>> {
        return scores
            .sortedByDescending { it.getScore() }
            .groupBy { it.word.category }
            .mapValues { it.value.take(10) }
    }

您现在可以在函数中以任意顺序传递您的 List<HighScore>,它将始终 return 高分按类别分组,从最高分开始排序,每组最多包含 10 个元素。