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.
CodePudding user response:
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.
CodePudding user response:
You can use groupingBy
and then fold
:
transactions.groupingBy(MoneyTransaction::category)
.fold(0.0) { acc, next -> acc next.amount }
groupingBy
here would return a Grouping<MoneyTransaction, String>
, which is an intermediate collection of the groups. Then you fold
each of the groups by starting from 0, and adding the next transaction's amount.
Looking at the implementation, the groupingBy
call doesn't actually does any actual "grouping" - it just creates a lazy Grouping
object. So effectively, you are going through the collection only once.