Reputation: 4020
How can I convert a Map<String, ArrayList<Int>>
to a Map<String, Int>
?
My objects are as follows:
val mapOfItems = mapOf("x" to listOf(1, 2), "y" to listOf(1, 3), "z" to listOf(2, 3))
I want to get an object like this:
val mapOfSummedItems = mapOf("x" to 3, "y" to 4, "z" to 5)
I tried:
mapOfItems.map { (key, value) -> SummedItems(key, value.sum()) }
.groupBy { it.key }
data class SummedItems(val key: String, val sum: Int)
That does not give me what I want that gives me an Map<String, ArrayList<SummedItems>>
Upvotes: 0
Views: 490
Reputation: 607
.map()
on a Map
generates a List
. While you can make this a List<Pair>
and then use associate*
operators to get back into a Map
, you can also just map the values directly:
mapOfItems.mapValues { it.value.sum() }
Upvotes: 4