I have a Map <String,List> map1 that looks like that
{First: ['1', '2', '3', '4'], Second: ['A', 'B']}
I want to create another Map<String,Map<String,int>> as a ruslt of values from map1 to be like that
{'1A' : ['String1':10,'String2':20], '1B' : ['String1':10,'String2':20] , '2A' : ['String1':10,'String2':20], '2B' : ['String1':10,'String2':20], '3A' : ['String1':10,'String2':20] , '3C' : ['String1':10,'String2':20]}
I hope you get my point
CodePudding user response:
- Similar question Generate all combinations from multiple lists
- Reference Source: https://stackoverflow.com/a/17193002/6576315
void main() async{
Map<String,List> rawMapList = {"First": ['1', '2', '3', '4'], "Second": ['A', 'B']};
List<Map<String, int>> mapResult = [{"String1" : 10}, {"String2" : 20}];
List<String> keyList = <String>[];
generatePermutations(rawMapList.values.toList(), keyList, 0, "");
var result = Map.fromEntries(keyList.map((value) => MapEntry(value, mapResult)));
print(result);
}
void generatePermutations(List<List<dynamic>> lists, List<String> result, int depth, String current) {
if (depth == lists.length) {
result.add(current);
return;
}
for (int i = 0; i < lists.elementAt(depth).length; i ) {
generatePermutations(lists, result, depth 1, current lists.elementAt(depth).elementAt(i));
}
}
Try first on DartPad, This code block will print
{1A: [{String1: 10}, {String2: 20}], 1B: [{String1: 10}, {String2: 20}], 2A: [{String1: 10}, {String2: 20}], 2B: [{String1: 10}, {String2: 20}], 3A: [{String1: 10}, {String2: 20}], 3B: [{String1: 10}, {String2: 20}], 4A: [{String1: 10}, {String2: 20}], 4B: [{String1: 10}, {String2: 20}]}
Do upvote reference
CodePudding user response:
the solution
Map<String, dynamic> data = {
'First': ['1', '2', '3', '4'],
'Second': ['A', 'B']
};
Map<String, dynamic> ans = {};
calculate() {
for (var i in (data['First'] as List<dynamic>)) {
for (var j in (data['Second'] as List<dynamic>)) {
ans.addAll({
"$i$j": [
{'String1': 10},
{'String2': 20}
],
});
}
}
log("$ans");
}