在dart地图中添加所有值 [英] Adding all the values in a map in dart

查看:69
本文介绍了在dart地图中添加所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将地图的所有值相加,使其总数为14000?

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,        
  };


推荐答案

首先,您只关心此地图的值,而不在乎键,因此我们按以下方式处理值:

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;

我们可以使用reduce将所有值与求和运算符组合在一起:

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);

您可以参考List&在此处映射:

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

这篇关于在dart地图中添加所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆