Dart -如何对Map的键排序

eiee3dmh  于 2023-06-27  发布在  其他
关注(0)|答案(6)|浏览(166)

我有问题在排序Map的关键在 dart 。

Map<String, Object> map = new Map();

我如何在Map中对密钥进行排序?或对可迭代Map键进行排序。

0sgqnhkj

0sgqnhkj1#

在Dart中,它被称为SplayTreeMap

import "dart:collection";

main() {
  final SplayTreeMap<String, Map<String,String>> st = 
      SplayTreeMap<String, Map<String,String>>();

  st["yyy"] = {"should be" : "3rd"};
  st["zzz"] = {"should be" : "last"};
  st["aaa"] = {"should be" : "first"};
  st["bbb"] = {"should be" : "2nd"};

  for (final String key in st.keys) {
    print("$key : ${st[key]}");
  }
}

// Output:
// aaa : first
// bbb : 2nd
// yyy : 3rd
// zzz : last
gmol1639

gmol16392#

如果你想要一个排序List的Map键:

var sortedKeys = map.keys.toList()..sort();

您可以选择将自定义排序函数传递给List.sort方法。
最后,我是否可以建议使用Map<String, dynamic>而不是Map<String, Object>

dgsult0t

dgsult0t3#

final sorted = SplayTreeMap<String,dynamic>.from(map, (a, b) => a.compareTo(b));

如所见
How to use a SplayTreeMap on Firebase snapshot dictionary in dart/Flutter?

s5a0g9ez

s5a0g9ez4#

我知道我的答案已经太迟了,但看看我发现了什么。也许能帮上什么人
这个sortedmap包有助于以排序的方式维护对象的Map。

5us2dqdw

5us2dqdw5#

map.entries.toList().sort(((a, b) => a.key.compareTo(b.key)));

我想是的。

ckx4rj1h

ckx4rj1h6#

我建议使用以下代码:

void main() {
  var x = {'b': 10, 'c': 7, 'a': 2};
  print('x = $x');
  
  final  y = x.orderByKeys(compareTo: (a, b) => a.compareTo(b));
  final  z = x.orderByValues(compareTo: (a, b) => a.compareTo(b));
  print('y = $y');
  print('z = $z');
  
  
}

/// Extensions on [Map] of <[dynamic], [dynamic]>
extension ExtendsionsOnMapDynamicDynamic on Map<dynamic, dynamic>{
  /// Order by keys
  Map<dynamic, dynamic> orderByKeys({required int Function(dynamic a, dynamic b) compareTo}) {
    return Map.fromEntries(entries.toList()..sort((a, b) => compareTo(a.key, b.key)));
  }

  /// Order by values
  Map<dynamic, dynamic> orderByValues({required int Function(dynamic a, dynamic b) compareTo}) {
    return Map.fromEntries(entries.toList()..sort((a, b) => compareTo(a.value, b.value)));
  }
}

相关问题