Christian
Christian

Reputation: 26427

How do I filter a Map in Dart so that all values are unique?

I have a list that's formatted like {0:"a", 1:"b", 2:"c", 3: "a"} and want to remove dublicate values so that I end up with {0:"a", 1:"b", 2:"c"}. I'm also fine with geting {1:"b", 2:"c", 3: "a"}. What's the most idiomatic way to do this filtering?

Upvotes: 0

Views: 548

Answers (2)

julemand101
julemand101

Reputation: 31269

If you want to change an existing map, you can do the following. I have made it as a extension method but you can of course also just have it as a separate method or some lines of codes:

extension RemoveDuplicateValuesExtension<K, V> on Map<K, V> {
  void removeDuplicateValues() {
    final valuesSoFar = <V>{};
    this.removeWhere((_, value) => !valuesSoFar.add(value));
  }
}

void main() {
  final map = {0: "a", 1: "b", 2: "c", 3: "a"}..removeDuplicateValues();
  print(map); // Prints: {0: a, 1: b, 2: c}
}

Upvotes: 1

jamesdlin
jamesdlin

Reputation: 90125

package:quiver provides a bidirectional map (BiMap) that makes it an error to add elements that don't have unique values.

Alternatively, one easy way to filter duplicate values is to create a separate Set of values and use it to rebuild the Map:

Map<K, V> removeDuplicateValues<K, V>(Map<K, V> map) {
  var valuesSoFar = <V>{};
  return {
    for (var mapEntry in map.entries)
      if (valuesSoFar.add(mapEntry.value)) mapEntry.key: mapEntry.value,
  };
}

void main() {
  var map = {0: "a", 1: "b", 2: "c", 3: "a"};
  print(removeDuplicateValues(map)); // Prints: {0: a, 1: b, 2: c}
}

Upvotes: 2

Related Questions