Search code examples
arrayslistelementuniquedart

How can I make Array (list) Elements Unique in Dart?


I need to remove redundant (String) elements from a list. Or perhaps to prevent them from being entered in the first place is the better solution? Sets do not allow duplicates, but they also do not keep order and I need the order. This is a common problem for me so I am looking for a possible language solution for full efficiency.

(In the past I have extended an Array Class to add my own add_unique() method, but this seems like it is a common enough issue to be handled by the language and likely more efficiently.)

Thanks,

_g


Solution

  • You need a LinkedSet to contain only uniques and keep insertion order, but currently we don't have it in dart. However you can emulate a LinkedSet using a LinkedHashMap:

    var input = ["apple", "orange", "cherries", "pears", "apple", "apple", "orange"];
    var uniques = new LinkedHashMap<String, bool>();
    for (var s in input) {
      uniques[s] = true;
    }
    for (var key in uniques.getKeys()) {
      print ("$key");
    }