Loading...

Group and add a list in kotlin

Answer #1 100 %

Let's define your shown entity as the following class:

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

Then we define the data structure of multiple entities:

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

Finally, a simple grouping and aggregating gives the desired response:

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
    }

Result:

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

You’ll also like:


© 2023 CodeForDev.com -