-2

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?

Samoilov
  • 488
  • 4
  • 14

2 Answers2

3

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]
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • No, I need only v left in your case – Samoilov Feb 14 '22 at 16:08
  • You are left with 1 option. If there are duplicates, then you need to delete them completely, and you will have 1 option – Samoilov Feb 14 '22 at 16:11
  • This option looks nice syntactically, but it will have a time complexity of O(n2) since it will loop over the full list for each item in the list. My approach will perform better, but this one is simpler to understand :) – Ruud van den Boomen Feb 14 '22 at 20:38
  • Well, I am not able to judge this, doing `forEach`, creating new map, finding with `containsKey` and again iterating map.; It describes the process But I prefer shortcut without errors. – Md. Yeasin Sheikh Feb 15 '22 at 04:52
1

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.