gpt4 book ai didi

collections - 如何在Kotlin中使用唯一的增量键对值进行分组?

转载 作者:行者123 更新时间:2023-12-02 13:13:06 26 4
gpt4 key购买 nike

例如,我有这样的列表:

{{1,"a"},{2,"a"},{3,"b"},{4,"b"},{5,"b"},{6,"a"},{7,"a"},{8,"a"}}

如果我使用Kotlin的 groupBy { it.value },它将像这样:
{
a: = {1,2,6,7,8},
b: = {3,4,5}
}

但我想这样分组:
{
a1: = {1,2},
b1: = {3,4,5},
a2: = {6,7,8}
}

我应该使用什么Kotlin的功能?

最佳答案

给定ListPair<Int, String>(因为顺序很重要),如下所示:

val list = listOf(1 to "a", 2 to "a", 3 to "b", 4 to "b", 5 to "b", 6 to "a", 7 to "a", 8 to "a")

您可以执行以下操作:
fun groupCount(list: List<Pair<Int, String>>): Map<String, List<Int>> {
val countMap = mutableMapOf<String, Int>()
var currentStr = list.firstOrNull()?.second ?: return emptyMap()

return list.map { (key, value) ->

if(currentStr != value) {
currentStr = value
countMap[value] = ((countMap[value] ?: 0) + 1)
}

key to value + countMap.getOrPut(value, {1})
}.groupBy ({it.second}, {it.first})
}

最后,当您需要打开Kotlin的 groupBy时,它特别方便

[(1, a1), (2, a1), (3, b1), (4, b1), (5, b1), (6, a2), (7, a2), (8, a2)]



到这个:

{a1=[1, 2], b1=[3, 4, 5], a2=[6, 7, 8]}



如果您碰巧有一个 Map<Int, String>,则可以在将其传递给 toList()之前调用 groupCount

关于collections - 如何在Kotlin中使用唯一的增量键对值进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54206615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com