Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)) }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading