0

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

  • amount
  • category

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

ShrikeThe
  • 77
  • 6

1 Answers1

1

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 } }
Sinner of the System
  • 2,558
  • 1
  • 8
  • 17
  • Niceee! :) This is exactly what I was looking for. Follow up question: what if amount was a Double and not an Int ? I am getting some type mismatch, I think sumBy is expecting Int? – ShrikeThe Jan 26 '21 at 22:17
  • Nvm found the sumByDouble function :) Still a follow up question: If one was to read this code statement in English how would that go? – ShrikeThe Jan 26 '21 at 22:22
  • I dont understand the question. Function names are descriptive. – Sinner of the System Jan 26 '21 at 23:02