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

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.

Leave a Reply