Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding all the values in a map in dart

Tags:

flutter

dart

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,        
  };
like image 233
Peter aziz Avatar asked Aug 28 '18 12:08

Peter aziz


People also ask

How do I add value to dart map?

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.

How do you add a list on map flutter?

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 .


1 Answers

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

like image 71
yelliver Avatar answered Sep 16 '22 22:09

yelliver