在 kotlin 中分组并添加列表

Jua*_*nza 3 android kotlin

如何在 Kotlin 中对列表进行分组并添加其值?

List =  [0]("06",80.30, 30 , 20 ,"ProductA","CANDY")
        [1]("06", 2.5 , 9 , 6 ,"ProductB","CANDY")
        [2]("07", 8 , 5.7 , 1 ,"ProductC","BEER")
        [3]("08", 10 , 2.10 , 40 ,"ProductD","PIZZA")
Run Code Online (Sandbox Code Playgroud)

并得到下一个结果

Result = ("06",82.8, 39 , 26,"CANDY")
         ("07", 8 , 5.7 , 1,"BEER")
         ("08", 10 , 2.10 , 40,"PIZZA")
Run Code Online (Sandbox Code Playgroud)

我将不胜感激您的帮助。

s1m*_*nw1 5

让我们将显示的实体定义为以下类:

data class Entity(
    val id: String,
    val d1: Double,
    val d2: Double,
    val i3: Int,
    val prod: String,
    val type: String
)
Run Code Online (Sandbox Code Playgroud)

然后我们定义多个实体的数据结构:

val entities = listOf(
        Entity("06", 80.30, 30.0, 20, "ProductA", "CANDY"),
        Entity("06", 2.5, 9.0, 6, "ProductB", "CANDY"),
        Entity("07", 8.0, 5.7, 1, "ProductC", "BEER"),
        Entity("08", 10.0, 2.10, 40, "ProductD", "PIZZA"))
Run Code Online (Sandbox Code Playgroud)

最后,一个简单的分组和聚合给出了所需的响应:

val aggregate = entities.groupingBy(Entity::id)
    .aggregate { _, accumulator: Entity?, element: Entity, _ ->
        accumulator?.let {
            it.copy(d1 = it.d1 + element.d1, d2 = it.d2 + element.d2, i3 = it.i3 + element.i3)
        } ?: element
    }
Run Code Online (Sandbox Code Playgroud)

结果:

{
 06=Entity(id=06, d1=82.8, d2=39.0, i3=26, prod=ProductA, type=CANDY), 
 07=Entity(id=07, d1=8.0, d2=5.7, i3=1, prod=ProductC, type=BEER), 
 08=Entity(id=08, d1=10.0, d2=2.1, i3=40, prod=ProductD, type=PIZZA)
}
Run Code Online (Sandbox Code Playgroud)