How to sort a Set<String> alphabetically in Dart/Flutter?
Solution 1
Use a SplayTreeSet
instead:
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
.
Solution 2
You can convert a set to a list and call the sort method. 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 reasons = {
'Peter',
'John',
'James',
'Luke',
};
final reasonsList = reasons.toList();
reasonsList.sort();
print(reasonsList.toSet());
Leonidas Yopan
Desv com Visão Sistêmica Sou um desenvolvedor frontend com uma visão sistêmica apurada e consequentemente busco usar minha prévia experiência empresarial para otimizar a capacidade das equipes que integro em sua capacidade de entrega e perspectiva do potencial dos resultados que nossa aplicação pode alcançar e dos impactos que terá em seus usuários. Ferramentas Favoritas HTML, CSS e JavaScript (vanilla) NodeJS ReactJS GitHub Illustrator Photoshop
Updated on December 24, 2022Comments
-
Leonidas Yopan over 1 year
I know there is the
List<string>
, but I need to use aSet<string>
. Is there a way to to sort it alphabetically?Set reasons = { 'Peter', 'John', 'James', 'Luke', }
-
jamesdlin over 3 yearsNote that although the example here explicitly passes a comparison callback (which I'm assuming is for demonstrative purposes), the callback isn't necessary if the elements are already
Comparable
(whichString
s are).