You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart列表元素出现次数统计及代码返回空Map问题排查

Dart列表元素出现次数统计问题解答

为什么你的代码返回空Map?

问题出在myList.map()方法的特性上:Dart中的map()是惰性执行的,它只会返回一个迭代器对象,不会主动执行你传入的回调函数。只有当你去遍历这个迭代器(比如调用toList()、forEach(),或者用for循环迭代)时,回调才会被触发执行。你当前的代码仅仅创建了这个map迭代器,但没有触发它,所以counts Map始终是空的。

正确的统计方法

方法1:使用forEach(最直观)

把map换成forEach,forEach会立即遍历列表并执行回调,直接修改counts Map:

void main() {
  final List myList = [
    'blue',
    'red',
    'amber',
    'blue',
    'green',
    'orange',
    'red',
    'blue',
    'pink',
    'amber',
    'blue',
  ];

  final Map counts = {};

  myList.forEach((e) => counts[e] = (counts[e] ?? 0) + 1);

  print(counts); // 输出: {blue: 4, red: 2, amber: 2, green: 1, orange: 1, pink: 1}
}

方法2:使用fold(函数式风格)

fold可以从初始值开始,通过迭代列表元素逐步累积结果,不需要额外定义空Map:

void main() {
  final List myList = [
    'blue',
    'red',
    'amber',
    'blue',
    'green',
    'orange',
    'red',
    'blue',
    'pink',
    'amber',
    'blue',
  ];

  final Map counts = myList.fold({}, (acc, element) {
    acc[element] = (acc[element] ?? 0) + 1;
    return acc;
  });

  print(counts);
}

方法3:触发原map迭代器(不推荐)

如果你非要保留map写法,需要触发迭代器执行,比如调用toList():

myList.map((e) => counts.containsKey(e) ? counts[e]++ : counts[e] = 1).toList();

不过这种写法不符合map的设计初衷(map是用来转换元素,不是执行副作用),所以不推荐使用。

内容的提问来源于stack exchange,提问作者Davoud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 12:22:55