Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map implementation with duplicate keys in Dart

Tags:

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
like image 637
flutter Avatar asked Oct 19 '25 02:10

flutter


2 Answers

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.

like image 150
julemand101 Avatar answered Oct 22 '25 03:10

julemand101


package:quiver provides a MultiMap class with List-based and Set-based implementations.

like image 28
jamesdlin Avatar answered Oct 22 '25 05:10

jamesdlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!