kotlinmutablelistmutablemap

MutableList to MutableMap in Kotlin


I have a mutable list of objects that belong to custom class Expense. Class Expense has following attributes:

I want to create a mutable map by iterating through the list above and the result should be as follows:

category_1 : sum of all amounts that had category_1 as category

category_2 : sum of all amounts that had category_2 as category

...

I am looking for a one-liner if possible. Kotlin idiomatic code.

This is what I have so far:

listOfExpenses.associateTo(expensesByCategory) {it.category to it.amount}

I need the last part: it.amount to somehow be a sum of all the amounts belonging to a certain category.

listOfExpenses is the list of Expense objects, expensesByCategory is the map I want to modify


Solution

  • I know this is more than one line but it does what you need

    val expensesByCategory = listOfExpenses
        .groupBy { it.category }
        .mapValues { it.value.sumBy { it.amount } }