'How to reverse a Map in dart? Is there any build in function
There is a map. I want to reverse it. is there any inbuilt function for that in dart?
{203: 5, 201: 3, 204: 1}
This the current Map i have.
{204: 1,201: 3:203: 5}
This is the results i want to get.
Thank You!
Solution 1:[1]
map.lenght should be map.length
thanks for your code
sort(Map map){
Map newmap;
for(int i =0 ; i< map.length; i++){
String x = map.entries.last.key.toString();
int y = map.entries.last.value;
newmap[x] = y;
map.remove(x);
}
return newmap;
}
Solution 2:[2]
Does this work? (I'm on mobile and can't test)
import 'dart:collection';
void main() {
final m = {203: 5, 201: 3, 204: 1};
final reverseM = LinkedHashMap.fromEntries(m.entries.toList().reversed);
print(reverseM);
}
Solution 3:[3]
If someone still need a solution, I wrote a simple library to deeply reverse Map
, Set
and List
. Usage is simple, because deepReverse()
is an extension method, so all you need to do is to import my library and call the method on your map:
import 'package:deep_collection/deep_collection.dart';
void main() {
print({203: 5, 201: 3, 204: 1}.deepReverse());
}
Solution 4:[4]
this doesn't handle the situation where values are duplicated, but if that's not an issue:
Map reverseMap(Map map) => {
for (var e in map.entries) e.value: e.key};
reverseMap({'a': 1, 'b': 2})
// {1: 'a', 2: 'b'}
Solution 5:[5]
this is the simplest way to reverse Map by its keys in Dart language:
reverseMap(Map map) {
Map newmap = {};
for (String _key in map.keys.toList().reversed) {
newmap[_key] = map[_key];
}
return newmap;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 | |
Solution 3 | Owczar |
Solution 4 | MetaStack |
Solution 5 | Hossein Vejdani |