Home > Back-end >  Remove duplicate dart
Remove duplicate dart

Time:02-15

there is a list:

@Koolkid3
@Peetea
@Peetea
@Ruptan
@bulunabu
@ptygma
@ptygma

Here's what to get:

@Koolkid3
@Ruptan
@bulunabu

If there are duplicates, then you need to remove them completely. Therefore, toSet() will not work here. How to do it?

CodePudding user response:

You can convert List to Set to remove duplicates. If needed again convert it into list.

 List<String> list = ["a", "v", "a"];

 print(list.toSet().toList()); //[a, v]

Removing duplicates and itself

List<String> list = ["a", "v", "a"];

list.removeWhere(
  (String s1) => list.where((s2) => s1 == s2).length > 1,
);

print(list); /// [v]

CodePudding user response:

What about the following:

  List<String> list = [
    "@Koolkid3",
    "@Peetea",
    "@Peetea",
    "@Ruptan",
    "@bulunabu",
    "@ptygma",
    "@ptygma"
  ];
  var occurrenceCount = Map();

  list.forEach((x) => occurrenceCount[x] = !occurrenceCount.containsKey(x) ? (1) : (occurrenceCount[x]   1));

  list.retainWhere((element) => occurrenceCount[element] == 1);
  print(list);

Use a Map to count occurrence of each item, then use retainWhere to only keep the items that occur once.

  • Related