如何在Dart中统一地图?

时间:2019-06-11 12:07:13

标签: dart

给出任何一个Iterable<Map>,我想得到一个Map,并将它们的所有组成部分合并为一个Set

例如:

  

{“ foo”:1,“ bar”:1},{“ bar”:2},{“ bar”:1,“ baz”:1},{“ bar”:2,“ foo”: 2}

应返回一个

  

{“ foo”:{1,2},“ bar”:{1,2},“ baz”:{1}}

我只是编写了代码,但问题是在SDK(或包中)中执行此常见任务的可用库

Map unifyMaps(Iterable<Map> values) {
if (values.isEmpty) {
  return null;
} else if (values.length == 1) {
  return values.single;
} else {
  Map ret = {};
  values.forEach((m) {
    m.forEach((k, v) {
      if (ret[k] == null) {
        ret[k] = {v};
      } else {
        ret[k].add(v);
      }
    });
  });
  return ret;
}

}

1 个答案:

答案 0 :(得分:1)

你在这里...

void main() {
  var inputs = [{"foo":1,"bar":1},{"bar":2},{"bar":1,"baz":1},{"bar":2,"foo":2}];
  print(inputs);
  print(unifyMaps(inputs));
}

Map<String, Set<T>> unifyMaps<T>(Iterable<Map<String, T>> source) {
  var result = <String, Set<T>>{};
  for (var entry in source.expand((m) => m.entries)) {
    result.putIfAbsent(entry.key, () => <T>{}).add(entry.value);
  }
  return result;
}

或者如果您想太花哨的话

Map<String, Set<T>> unifyMaps<T>(Iterable<Map<String, T>> source) =>
    source.expand((m) => m.entries).fold(
        <String, Set<T>>{},
        (result, entry) =>
            result..putIfAbsent(entry.key, () => <T>{}).add(entry.value));