Answer the question
In order to leave comments, you need to log in
How to sum two collections by keys and values?
Hello.
There is a collection:
private val ABC: MutableMap<Int, Int> = mutableMapOf()
fun addABC(type: Enum<Type>, denomination: Int, amount: Int) {
when (type) {
Type.ABC -> {
ABC += ABC.put(denomination, amount)
}
}
}
Answer the question
In order to leave comments, you need to log in
I propose such an implementation of a function that allows you to add multiple instances of Map. If you need something more universal (for example, with addition not only Int) - look towards generics.
fun mapsSum(vararg maps: Map) = maps
.map { it.toList() }.flatten() // Convert all Maps to a Pair list
.groupBy { it.first } // Group by unique keys
.map { (key, pairList) -> pairList.sumBy { it.second } } // Calculate the sum for each key
fun main() {
val firstABC = mutableMapOf(1 to 2, 2 to 5)
val secondABC = mutableMapOf(1 to 5)
println(mapsSum (firstABC, secondABC))
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question