如何在 Dart/Flutter 中按字母顺序对 Set<String> 进行排序?

Leo*_*pan 6 set dart flutter

我知道有List<string>,但我需要使用Set<string>。有没有办法按字母顺序排序?

Set reasons = {
  'Peter',
  'John',
  'James',
  'Luke',
}
Run Code Online (Sandbox Code Playgroud)

Abi*_*n47 15

使用 aSplayTreeSet代替:

import 'dart:collection';

...

final sortedSet = SplayTreeSet.from(
  {'Peter', 'John', 'James', 'Luke'},
  // Comparison function not necessary here, but shown for demonstrative purposes 
  (a, b) => a.compareTo(b), 
);
print(sortedSet);

// Prints: {James, John, Luke, Peter}
Run Code Online (Sandbox Code Playgroud)

正如 jamesdlin 指出的那样,如果类型实现了Comparable.


Tir*_*tel 5

您可以将集合转换为列表并调用排序方法。然后您可以再次将该列表转换为集合。您还可以在 Set 上创建一个方便的扩展方法来执行相同的操作。

Set reasons = {
  'Peter',
  'John',
  'James',
  'Luke',
};
final reasonsList = reasons.toList();
reasonsList.sort();
print(reasonsList.toSet());
Run Code Online (Sandbox Code Playgroud)