Dart:按其值对地图的条目进行排序

想象一下你的老板给了你一张这样的 Dart 地图:

final Map<String, int> myMap = {
  'a': 10, 
  'b': 20, 
  'c': 15, 
  'd': 5, 
  'e': 14
};

然后他要求您按地图值的升序/降序对地图进行排序。你如何解决这个问题并让他开心?好吧,解决方案很简单。让我们看看下面的两个例子。

按值的升序对地图进行排序

编码:

// KindaCode.com
void main() {
  final Map<String, int> myMap = {'a': 10, 'b': 20, 'c': 15, 'd': 5, 'e': 14};

  // sort the map in the ascending order of values

  // turn the map into a list of entries
  List<MapEntry<String, int>> mapEntries = myMap.entries.toList();

  // sort the list
  mapEntries.sort((a, b) => a.value.compareTo(b.value));

  // turn the list back into a map
  final Map<String, int> sortedMapAsc = Map.fromEntries(mapEntries);

  // print the result
  print(sortedMapAsc);
}

输出:

{d: 5, a: 10, e: 14, c: 15, b: 20}

按值的降序对地图进行排序

代码与前面的示例几乎相同,只是我们更改了这一行:

mapEntries.sort((a, b) => a.value.compareTo(b.value));

对此:

mapEntries.sort((a, b) => b.value.compareTo(a.value));

这是完整的代码:

// KindaCode.com
void main() {
  final Map<String, int> myMap = {'a': 10, 'b': 20, 'c': 15, 'd': 5, 'e': 14};

  // sort the map in the ascending order of values

  // turn the map into a list of entries
  List<MapEntry<String, int>> mapEntries = myMap.entries.toList();

  // sort the list in descending order of values
  mapEntries.sort((a, b) => b.value.compareTo(a.value));

  // turn the list back into a map
  final Map<String, int> sortedMapAsc = Map.fromEntries(mapEntries);

  // print the result
  print(sortedMapAsc);
}

输出:

{b: 20, c: 15, e: 14, a: 10, d: 5}