在kotlin中分组并添加一个列表

时间:2018-03-27 00:23:24

标签: 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")

并获得下一个结果

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

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

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

data class Entity(
    val id: String,
    val d1: Double,
    val d2: Double,
    val i3: Int,
    val prod: String,
    val type: String
)

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

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"))

最后,一个简单的分组和聚合可以得到所需的响应:

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
    }

结果:

{
 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)
}