N
N
ngapp2021-03-02 23:37:42
Kotlin
ngapp, 2021-03-02 23:37:42

How to sum two collections by keys and values?

Hello.
There is a collection:

private val ABC: MutableMap<Int, Int> = mutableMapOf()


there is a function
fun addABC(type: Enum<Type>, denomination: Int, amount: Int) {
            when (type) {
                Type.ABC -> {
                    ABC += ABC.put(denomination, amount)
                }
            }
        }


How to add values ​​of a new collection to an already existing collection in a function?
That is, do ABC(1=2) + ABC(2=5) + ABC(1=5) = ABC(1=7, 2=5)

Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Chetverikov, 2021-04-10
@Cheverikov_vv

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 question

Ask a Question

731 491 924 answers to any question