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

mapping custom object kotlin

I have a custom object:

data class MoneyTransaction(
    val amount: Double,
    val category: String
)

I have a list of MoneyTransaction. I want to create a map out of that list where keys are categories, and the values are the total amount according to the category. Kotlin has functions like groupBy, groupByTo, groupingBy. But there is no tutorial or documentation about those, so I can’t figure it out. So far I got this:

 val map = transactionList.groupBy({it.category},{it.amount})

But this doesn’t give the total amount, just separate amounts on each category

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

Any help would be much appreciated.

>Solution :

So first of all you group your transactions by category

transactionList.groupBy { it.category }

this gives you a Map<String, List<MoneyTransaction>> after that you need to sum up the amounts

transactionList.groupBy { it.category }
  .mapValues { (_, transactionsInCategory) -> 
    transactionsInCategory.sumOf { it.amount }
  }

This will give you a Map<String, Double> with the value representing the sum of all transactions in the category.

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