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

2,493

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());
Share:
2,493
Leonidas Yopan
Author by

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, 2022

Comments

  • Leonidas Yopan
    Leonidas Yopan over 1 year

    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',
    }
    
  • jamesdlin
    jamesdlin over 3 years
    Note 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 (which Strings are).