Search code examples
kotlinkotlin-extension

Kotlin - How to add counts of duplicate elements in a list to generate another list


I have a simple problem but I cant seem to use predefined methods in Kotlin to be able to do this. Here is what I am trying to solve.

data class A(val id: Int, val amount: Int)

private List<A> generateTotal(listOfA : List<A>)

The list has a couple of duplicate ids in it. For example :

A(1, 2), A(1,3), A(2,1)

generateTotal should return A(1, 5) and A(2,1) where the 2 elements in the above list have been summed.

Is this doable using some of Kotlin's existing functions?

Thanks


Solution

  • This should do it. First group by ID. The values of the resulting Map are lists of items with the same ID, so we can map these lists into single items.

    private fun generateTotal(listOfA: List<A>): List<A> =
        listOfA.groupBy(A::id)
            .values.map { A(it[0].id, it.sumOf(A::amount)) }