如何删除飞镖列表中的重复项?list.distinct()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12030613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:52:53  来源:igfitidea点击:

How to delete duplicates in a dart List? list.distinct()?

listdart

提问by Gero

How do i delete duplicates from a list without fooling around with a set? Is there something like list.distinct()? or list.unique()?

如何从列表中删除重复项而不用玩弄集合?有类似 list.distinct() 的东西吗?或 list.unique()?

void main() {
  print("Hello, World!");

  List<String> list = ['abc',"abc",'def'];
  list.forEach((f)=>print("this is list $f"));

  Set<String> set = new Set<String>.from(list);
  print("this is #0 ${list[0]}");
  set.forEach((f)=>print("set: $f"));

  List<String> l2= new List<String>.from(set);
  l2.forEach((f)=>print("This is new $f"));

}


Hello, World!
this is list abc
this is list abc
this is list def
this is #0 abc
set: abc
set: def
This is new abc
This is new def

Edit: thx for the answers. Setseems to be way faster!!, but it loses the order of the items :/

编辑:感谢答案。 设置似乎更快!!,但它失去了项目的顺序:/

采纳答案by John Evans

I have a library called Reactive-Dartthat contains many composable operators for terminating and non-terminating sequences. For your scenario it would look something like this:

我有一个名为Reactive-Dart的库,其中包含许多用于终止和非终止序列的可组合运算符。对于您的场景,它看起来像这样:

final newList = [];
Observable
   .fromList(['abc', 'abc', 'def'])
   .distinct()
   .observe((next) => newList.add(next), () => print(newList));

Yielding:

产量:

[abc, def]

I should add that there are other libraries out there with similar features. Check around on github and I'm sure you'll find something suitable.

我应该补充一点,还有其他具有类似功能的库。在 github 上四处看看,我相信你会找到合适的。

回答by atreeon

Use toSetand then toList

使用toSet然后toList

  var ids = [1, 4, 4, 4, 5, 6, 6];
  var distinctIds = ids.toSet().toList();

[1, 4, 5, 6]

[1, 4, 5, 6]

回答by Maria Miller

Setworks okay, but it doesn't preserve the order. Here's another way using LinkedHashSet:

Set工作正常,但它不保留顺序。这是另一种使用方法LinkedHashSet

import "dart:collection";

void main() {
  List<String> arr = ["a", "a", "b", "c", "b", "d"];
  List<String> result = LinkedHashSet<String>.from(arr).toList();
  print(result); // => ["a", "b", "c", "d"]
}

https://api.dart.dev/stable/2.4.0/dart-collection/LinkedHashSet/LinkedHashSet.from.html

https://api.dart.dev/stable/2.4.0/dart-collection/LinkedHashSet/LinkedHashSet.from.html

回答by Niko Ruotsalainen

If you want to keep ordering or are dealing with more complex objects than primitive types. Store seen ids to the Setand filter away those ones that are already in the set.

如果您想保持排序或处理比原始类型更复杂的对象。将看到的 id 存储到Set并过滤掉那些已经在集合中的ID 。

final list = ['a', 'a', 'b'];
final seen = Set<String>();
final unique = list.where((str) => seen.add(str)).toList();

print(unique); // => ['a', 'b']

回答by jtlim

Using dart 2.3+, you can use the spread operators to do this:

使用 dart 2.3+,您可以使用扩展运算符来执行此操作:

final ids = [1, 4, 4, 4, 5, 6, 6]; 
final distinctIds = [...{...ids}];

Whether this is more or less readable than ids.toSet().toList()I'll let the reader decide :)

这比ids.toSet().toList()我让读者决定的可读性强还是弱:)

回答by Cutch

void uniqifyList(List<Dynamic> list) {
  for (int i = 0; i < list.length; i++) {
    Dynamic o = list[i];
    int index;
    // Remove duplicates
    do {
      index = list.indexOf(o, i+1);
      if (index != -1) {
        list.removeRange(index, 1);
      }
    } while (index != -1);
  }
}

void main() {
  List<String> list = ['abc', "abc", 'def'];
  print('$list');
  uniqifyList(list);
  print('$list');
}

Gives output:

给出输出:

[abc, abc, def]
[abc, def]

回答by AleksTi

Here it is working solution:

这是工作解决方案:

var sampleList = ['1', '2', '3', '3', '4', '4'];
//print('orignal: $sampleList');
sampleList = Set.of(sampleList).toList();
//print('processed: $sampleList');

Output:

输出:

orignal: [1, 2, 3, 3, 4, 4]
processed: [1, 2, 3, 4]

回答by Anandu YD

try the following

尝试以下

List<String> duplicates = ["a","c","a"];

duplicates = duplicates.toSet().toList();

check the Darpad link - https://dartpad.dev/4d3a724429bbd605f4682b7da253a16e

检查 Darpad 链接 - https://dartpad.dev/4d3a724429bbd605f4682b7da253a16e

回答by Stanislav Sagan

As for me one of best practices is sort array, then deduplicate it. Idea is stolen from low level languages. So,

对于我来说,最佳实践之一是对数组进行排序,然后对其进行重复数据删除。想法是从低级语言中窃取的。所以,

first make sort by your own, then deduplicate equal values that are going after each other.

首先按您自己的方式进行排序,然后对相互追逐的相等值进行重复数据删除。

// easy example
void dedup<T>(List<T> list, {removeLast: true}) {
  int shift = removeLast ? 1 : 0;
  T compareItem;
  for (int i = list.length - 1; i >= 0; i--) {
    if (compareItem == (compareItem = list[i])) {
      list.removeAt(i + shift);
    }
  }
}

// harder example
void dedupBy<T, I>(List<T> list, I Function(T) compare, {removeLast: true}) {
  int shift = removeLast ? 1 : 0;
  I compareItem;
  for (int i = list.length - 1; i >= 0; i--) {
    if (compareItem == (compareItem = compare(list[i]))) {
      list.removeAt(i + shift);
    }
  }
}


void main() {
  List<List<int>> list = [[1], [1], [2, 1], [2, 2]];
  print('$list');
  dedupBy(list, (innerList) => innerList[0]);
  print('$list');

  print('\n removeLast: false');

  List<List<int>> list2 = [[1], [1], [2, 1], [2, 2]];
  print('$list2');
  dedupBy(list2, (innerList) => innerList[0], removeLast: false);
  print('$list2');
}

Output:

输出:

[[1], [1], [2, 1], [2, 2]]
[[1], [2, 1]]

removeLast: false
[[1], [1], [2, 1], [2, 2]]
[[1], [2, 2]]