如何对地图的值进行排序?

How to sort map's values?

有人可以给我提示吗?我想按列表的长度对地图的值进行排序。

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]
};

这样的东西可能适合你:

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]}');
});

一个函数,它根据长度对列表的映射进行排序。

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;
}

结果:

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] }

使用 DART 语言:

假设您要使用整数键和 Foo 类型的值对 Map 进行排序:

class Foo {
  int x; //it can be any type
}

所以你可以获得所有条目的列表,像普通列表一样对它们进行排序,然后重建映射:

Map<int, Foo> map = //fill map

var entries = map.entries.toList();
entries.sort((MapEntry<int, Foo> a, MapEntry<int, Foo> b) => a.value.x.compareTo(b.value.x));
map = Map<int, Foo>.fromEntries(entries);

基于@Leonardo Rignanese 的回答。更实用方法的扩展功能:

extension MapExt<T, U> on Map<T, U> {
  Map<T, U> sortedBy(Comparable value(U u)) {
    final entries = this.entries.toList();
    entries.sort((a, b) => value(a.value).compareTo(value(b.value)));
    return Map<T, U>.fromEntries(entries);
  }
}

一般用法:

foos.sortedBy((it) => it.bar);

OP 的用法:

final sortedChordtypes = chordtypes.sortedBy((it) => it.length);

此处要点:https://gist.github.com/nmwilk/68ae0424e848b9f05a8239db6b708390