How to add all the values of a map to have the total of 14000?
Map<String, int> salary = {
"user1": 4000,
"user2": 4000,
"user3": 3000,
"user4": 3000,
};
Using addAll() method It will add all key/value pairs of a map to another map. If a key already exists, its value will be overwritten.
Using Map forEach() methodmap. forEach((k, v) => list. add(Customer(k, v))); print(list); In the code above, we create a new Customer object from each key-value pair, then add the object to the list .
Firstly, you just care about the values of this map, not care about the keys, so we work on the values by this:
var values = salary.values;
And we can use reduce to combine all the values with sum operator:
var values = salary.values;
var result = values.reduce((sum, element) => sum + element);
print(result);
You can reference some basic of List & Map here:
https://api.dartlang.org/stable/1.10.1/dart-core/List-class.html https://api.dartlang.org/stable/1.10.1/dart-core/Map-class.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With