ShrikeThe
ShrikeThe

Reputation: 89

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

Upvotes: 0

Views: 487

Answers (1)

Sinner of the System
Sinner of the System

Reputation: 2966

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 } }

Upvotes: 1

Related Questions