I have a map with String,double and I want to sort this map based on its value and want to take only first 4 key value pair..like following
Map<String,dynamic> mymap={
'A':2000,
'B':8000,
'C':300,
'D':3890,
'E':8030,
'F':300,
'G':900,
};
and I want to convert into following
Map<String,dynamic> resultmap={
'E':8030,
'B':8000,
'D':3890,
'A':2000,
'Others':1500,
};
CodePudding user response:
To sort a map in descending order by value, you can use something like below (look here for more info).
var numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4};
print(numbers); // {one: 1, two: 2, three: 3, four: 4}
final sortedValuesDesc = SplayTreeMap<String, dynamic>.from(
numbers, (keys1, keys2) => numbers[keys2]!.compareTo(numbers[keys1]!));
print(sortedValuesDesc); // {four: 4, three: 3, two: 2, one: 1}
To get the sum of the rest of the values, there are some different options to choose from. I found this approach here on Stack Overflow:
final sum = numbers
.values
.skip(4)
.reduce((value, element) => value element);
What remains is to make sure the summed elements are removed and the above sum is added to the map along with your desired key.
Let me know if this worked for you. :-)
CodePudding user response:
You can do this in several steps.
First declare your map.
Map<String,dynamic> mymap={
'A':2000,
'B':8000,
'C':300,
'D':3890,
'E':8030,
'F':300,
'G':900,
};
Then, sorting the declared map in descending order by using this code.
var sortedList = mymap.entries.toList()..sort((b,a)=>a.value.compareTo(b.value));
Then, create a new map and add the sorted list as entries inside the new map.
Map newMap={};
newMap.addEntries(mapList);
Now, find other number's sum using this code.
int otherNumbersSum = newMap.values.skip(4).reduce((value, element) => value element);
Finally, create a new map and add entries in that map by checking that either they are three digits or four digits and at last adding the sum which we got in the last step.
Map finalMap ={};
for(var a in newMap.entries){
if(a.value>999){
finalMap[a.key] = a.value;
}
}
finalMap["Others"] = otherNumbersSum;
You will get result like this.
finalMap ={
'E':8030,
'B':8000,
'D':3890,
'A':2000,
'Others':1500,
};
Hope it will help :)