How to sort a Set<String> alphabetically in Dart/Flutter?

Viewed 3461

I know there is the List<string>, but I need to use a Set<string>. Is there a way to to sort it alphabetically?

Set reasons = {
  'Peter',
  'John',
  'James',
  'Luke',
}
2 Answers

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.

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());
Related