[英]How to sort a Set<String> alphabetically in Dart/Flutter?
I know there is the List<string>
, but I need to use a Set<string>
.我知道有
List<string>
,但我需要使用Set<string>
。 Is there a way to to sort it alphabetically?有没有办法按字母顺序排序?
Set reasons = {
'Peter',
'John',
'James',
'Luke',
}
Use a SplayTreeSet
instead:使用
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}
As jamesdlin points out, the comparison function is not necessary if the type implements Comparable
.正如 jamesdlin 指出的那样,如果类型实现
Comparable
则不需要比较函数。
You can convert a set to a list and call the sort method.您可以将集合转换为列表并调用 sort 方法。 Then you can convert that list to a set again.
然后您可以再次将该列表转换为集合。 You can also create a handy extension method on Set that does the same thing.
你也可以在 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.