dart

Map implementation with duplicate keys in Dart


I want to have a map with duplicate keys. Is there such a map in Dart or a utility library that has this functionality?

I'm using the following get a count of items:

myList.forEach(
      (element) {
        if (!myMap.containsKey(element)) {
          myMap[element] = 1;
        } else {
          myMap[element] += 1;
        }
      },
    );

then convert keys/values to lists: Need to switch key/values...

final keys = myMap.keys.toList();
final itemSpit = keys.map((e) => e.toString().split('§º')).toList();
final values = myMap.values.toList();

put it in a map

final map = Map();

    for (var i = 0; i < values.length; i++) {
      map[values[i]] = itemSpit[i];
    }

Obviously the keys are overridden in the for loop.

then iterate over map (Put keys/values in flutter widgets)

final cells = map.entries
        .map((e) => ........

THe first method increases the value count if there's a duplicate value. So I have this. ... {breadwhitelarge: 3, cornyellowsmall:5 ..etc..}

I then have to split the strings and have output like this

5 bread white large
3 corn yellow small

Solution

  • Instead of defining a map which allows duplicated keys you can instead create a Map<K,List<V>> like this example:

    void main() {
      final map = <String, List<int>>{};
    
      addValueToMap(map, 'Test 1', 1);
      addValueToMap(map, 'Test 1', 2);
      addValueToMap(map, 'Test 2', 3);
      addValueToMap(map, 'Test 1', 4);
      addValueToMap(map, 'Test 2', 5);
      addValueToMap(map, 'Test 3', 6);
    
      print(map); // {Test 1: [1, 2, 4], Test 2: [3, 5], Test 3: [6]}
    }
    
    void addValueToMap<K, V>(Map<K, List<V>> map, K key, V value) =>
        map.update(key, (list) => list..add(value), ifAbsent: () => [value]);
    

    You can then ask for a given key and get a list of all values connected to this key.