可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Can someone give me a hint? I want to sort a map's values by the length of the lists.
var chordtypes = {
"maj": [0, 4, 7],
"M7": [0, 4, 7, 11],
"m7": [0, 3, 7, 10],
"6": [0, 4, 7, 9],
"9": [0, 4, 7, 10, 14],
"sus2": [0, 2, 7],
"sus4": [0, 5, 7],
"omit3": [0, 7],
"#5": [0, 4, 8],
"+7b9#11": [0, 4, 8, 10, 13, 18],
"+9": [0, 4, 8, 10, 14]
};
回答1:
A function that does sort a Map of List on their length.
import 'dart:collection';
/// sorts the ListMap (== A Map of List<V>) on the length
/// of the List values.
LinkedHashMap sortListMap(LinkedHashMap map) {
List mapKeys = map.keys.toList(growable : false);
mapKeys.sort((k1, k2) => map[k1].length - map[k2].length);
LinkedHashMap resMap = new LinkedHashMap();
mapKeys.forEach((k1) { resMap[k1] = map[k1] ; }) ;
return resMap;
}
result for :
var res = sortListMap(chordtypes);
print(res);
==>
{ omit3: [0, 7],
maj: [0, 4, 7],
sus2: [0, 2, 7],
sus4: [0, 5, 7],
#5: [0, 4, 8],
M7: [0, 4, 7, 11],
m7: [0, 3, 7, 10],
6: [0, 4, 7, 9],
9: [0, 4, 7, 10, 14],
+9: [0, 4, 8, 10, 14],
+7b9#11: [0, 4, 8, 10, 13, 18] }
回答2:
Something like this could work for you:
Map chordtypes = {
"maj": [0, 4, 7],
"M7": [0, 4, 7, 11],
"m7": [0, 3, 7, 10],
"6": [0, 4, 7, 9],
"9": [0, 4, 7, 10, 14],
"sus2": [0, 2, 7],
"sus4": [0, 5, 7],
"omit3": [0, 7],
"#5": [0, 4, 8],
"+7b9#11": [0, 4, 8, 10, 13, 18],
"+9": [0, 4, 8, 10, 14]
};
List keys = chordtypes.keys.toList();
keys.sort((k1, k2) {
if(chordtypes[k1].length > chordtypes[k2].length)
return -1;
if(chordtypes[k1].length < chordtypes[k2].length)
return 1;
return 0;
});
keys.forEach((String k) {
print('$k ${chordtypes[k]}');
});
回答3:
import "package:queries/collections.dart";
void main() {
var chordtypes = {
"maj": [0, 4, 7],
"M7": [0, 4, 7, 11],
"m7": [0, 3, 7, 10],
"6": [0, 4, 7, 9],
"9": [0, 4, 7, 10, 14],
"sus2": [0, 2, 7],
"sus4": [0, 5, 7],
"omit3": [0, 7],
"#5": [0, 4, 8],
"+7b9#11": [0, 4, 8, 10, 13, 18],
"+9": [0, 4, 8, 10, 14]
};
var dict = new Dictionary<String, List>.fromMap(chordtypes);
// Sort by list length, then by key
var sorted = dict
.orderBy((kv) => kv.value, (a, b) => b.length.compareTo(a.length))
.thenBy((kv) => kv.key, (a, b) => a.compareTo(b));
dict = sorted.toDictionary((kv) => kv.key, (kv) => kv.value);
for (var kv in dict) {
print("$kv");
}
}
Sorted by [listLength, key]
+7b9#11 : [0, 4, 8, 10, 13, 18]
+9 : [0, 4, 8, 10, 14]
9 : [0, 4, 7, 10, 14]
6 : [0, 4, 7, 9]
M7 : [0, 4, 7, 11]
m7 : [0, 3, 7, 10]
#5 : [0, 4, 8]
maj : [0, 4, 7]
sus2 : [0, 2, 7]
sus4 : [0, 5, 7]
omit3 : [0, 7]