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?
3
Answers
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.
Updated
If you want to retain both values in the merged map, even if they have the same key, you can use a List
The Key is unique,so you need reSet key Value.