[英]How to sort a Set<String> alphabetically in Dart/Flutter?
我知道有List<string>
,但我需要使用Set<string>
。 有没有办法按字母顺序排序?
Set reasons = {
'Peter',
'John',
'James',
'Luke',
}
使用SplayTreeSet
代替:
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}
正如 jamesdlin 指出的那样,如果类型实现Comparable
则不需要比较函数。
您可以将集合转换为列表并调用 sort 方法。 然后您可以再次将该列表转换为集合。 你也可以在 Set 上创建一个方便的扩展方法来做同样的事情。
Set reasons = {
'Peter',
'John',
'James',
'Luke',
};
final reasonsList = reasons.toList();
reasonsList.sort();
print(reasonsList.toSet());
void main() {
Set names = {'Seth', 'Kathy', 'Lars', 'Katie', 'Sharon'};
List newlist = names.toList();
newlist.sort();
Set newset = newlist.toSet();
print(newset);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.