web-dev-qa-db-ja.com

ダーツリストの重複を削除する方法list.distinct()?

セットをだまさずにリストから重複を削除するにはどうすればよいですか? 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

編集:thxの答え。 セットの方が速いようですが、アイテムの順序が失われます:/

25
Gero

Reactive-Dart と呼ばれるライブラリーがあります。これには、シーケンスの終了および非終了のための多くの構成可能な演算子が含まれています。シナリオでは、次のようになります。

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

降伏:

[abc, def]

同様の機能を持つ他のライブラリーがあることを付け加えておきます。 GitHubをチェックしてみてください。適切なものが見つかるはずです。

4
John Evans

toSetを使用し、次にtoListを使用します

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

[1、4、5、6]

111
atreeon

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

21
Maria Miller

順序を維持したい場合、またはプリミティブ型よりも複雑なオブジェクトを処理している場合。表示されたIDを Set に保存し、すでにセットに含まれているものをフィルターで除外します。

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

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

8

queries パッケージを使用してみてください。

import 'package:queries/collections.Dart';

void main() {
  List<String> list = ["a", "a", "b", "c", "b", "d"];
  var result = new Collection(list).distinct();
  print(result.toList());
}
[a, b, c, d]
7
mezoni
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');
}

出力を提供します:

[abc, abc, def]
[abc, def]
4
Cutch

Dart 2.3以降では、spread演算子を使用してこれを行うことができます。

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

これがids.toSet().toList()より読みやすいかどうかは、読者に判断させてください:)

4
jtlim

ここでそれは実用的なソリューションです:

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

出力:

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

私にとってのベストプラクティスの1つは、配列の並べ替えで、それを重複排除します。低レベルの言語からアイデアが盗まれます。そう、

最初に自分でソートしてから、次に優先される同じ値を重複排除します。

// 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');
}

出力:

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

removeLast: false
[[1], [1], [2, 1], [2, 2]]
[[1], [2, 2]]
0
Stanislav Sagan