Home > Software design >  How to merge map with same key
How to merge map with same key

Time:12-31

How to merge a map with same key?

Codes

void main() {
  
  final test1 = <int>[1];
  final test2 = <int>[1];
  final test3 = List.of(test1)..addAll(test2);
  
  print('Rifa 1: ${test1.length}');
  print('Rifa 2: ${test2.length}');
  print('Rifa 3: ${test3.length}');
  print('-----------------------');
  
  
  final test4 = {'rifa':'aaa'};
  final test5 = {'rifa':'bbb'};
  final test6 = Map.of(test4)..addAll(test5);
  
  print('Rifa 4: ${test4.length}');
  print('Rifa 5: ${test5.length}');
  print('Rifa 6: ${test6.length}');
  print('-----------------------');
  
  
  final test7 = {'name':'rifa'};
  final test8 = {'name1':'rifa'};
  final test9 = Map.of(test7)..addAll(test8);
  
  print('Rifa 7: ${test7.length}');
  print('Rifa 8: ${test8.length}');
  print('Rifa 9: ${test9.length}');
 
 
}

And this is the result from above code:

Rifa 1: 1
Rifa 2: 1
Rifa 3: 2
-----------------------
Rifa 4: 1
Rifa 5: 1
Rifa 6: 1
-----------------------
Rifa 7: 1
Rifa 8: 1
Rifa 9: 2

As you can see above in test6 variable, I make merged a map with the same key but diff/same value and the result is only 1 data. But I need it as 2 data even if it's a duplicate key. It is possible?

CodePudding user response:

The Key is unique,so you need reSet key Value.

final test4 = {'rifa': 'aaa'};
      final test5 = {'rifa': 'bbb'};
      var temp = <String, String>{};
      var count = 0;
      test4.forEach((key, value) {
        count  ;
        if (test5.keys.contains(key)) {
          temp.putIfAbsent('index_${count}_$key', () => value);
        }
      });
      final test6 = Map.of(test4)
        ..addAll(test5)
        ..addAll(temp);

CodePudding user response:

In a Map is not possible to have duplicate keys.

If you want to have duplicate keys in a map, you can use e.g. mergedMap.

  final test4 = {'rifa':'aaa'};
  final test5 = {'rifa':'bbb'};
  final test6 = [test4, test5];
  
  final mergedMap = <String, String>{};
  test6.forEach((map) {
    mergedMap.addAll(map);
  });
  
  print(mergedMap); // {'rifa': 'bbb'}
}

Updated

If you want to retain both values in the merged map, even if they have the same key, you can use a List

  final test4 = {'rifa':'aaa'};
  final test5 = {'rifa':'bbb'};
  final test6 = [test4, test5];
  
  final mergedMap = <String, List<String>>{};
  test6.forEach((map) {
    map.forEach((key, value) {
      if (mergedMap.containsKey(key)) {
        mergedMap[key].add(value);
      } else {
        mergedMap[key] = [value];
      }
    });
  });
  
  print(mergedMap); // {'rifa': ['aaa', 'bbb']}
}

CodePudding user response:

How to merge a map with same key?

To merge two maps and keep all of the key-value pairs, even if the maps have duplicate keys, you can use the Map.fromIterables method.

Example

  • With Duplicate Keys
final test4 = {'rifa': 'aaa'};
final test5 = {'rifa': 'bbb'};

final keys = test4.keys.toList()   test5.keys.toList();
final values = test4.values.toList()   test5.values.toList();

final test6 = Map.fromIterables(keys, values);

print(test6); // Output: {'rifa': 'bbb'}

Note!

It is not possible to create a map with duplicate keys using the Map class. The Map class does not allow you to add a key-value pair to a map if the map already contains a key that is equal to the key in the key-value pair.

To create a map with duplicate keys, you can use a different data structure, such as a list of key-value pairs.

void main (){
 
  final test4 = {'rifa': 'aaa'};
  final test5 = {'rifa': 'bbb'};

  final keyValuePairs = test4.entries.toList()   test5.entries.toList();

  print(keyValuePairs); // Output: [MapEntry('rifa', 'aaa'), 
                        // MapEntry('rifa', 'bbb')]
  print(keyValuePairs.length); // Output: 2
}

Here is an example using a custom Pair class

class Pair {
  final String key;
  final String value;

  Pair(this.key, this.value);
}

void main() {
  final test4 = {'rifa': 'aaa'};
  final test5 = {'rifa': 'bbb'};

  final pairs = <Pair>[];
  test4.forEach((key, value) => pairs.add(Pair(key, value)));
  test5.forEach((key, value) => pairs.add(Pair(key, value)));

  print(pairs); // Output: [Pair(key: 'rifa', value: 'aaa'), Pair(key: 'rifa', value: 'bbb')]
}

Demo

  • Related