How to remove duplicates from the list without cheating yourself with a set? Is there something like list.distinct ()? or 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: thanks for the answers. Install seems to be faster !!!, but it loses the order of the elements: /
I have a library called Reactive-Dart that contains many compound statements for trailing and non-ending sequences. For your scenario, it will look something like this:
final newList = []; Observable .fromList(['abc', 'abc', 'def']) .distinct() .observe((next) => newList.add(next), () => print(newList));
Yielding:
[abc, def]
I must add that there are other libraries with similar features. Check on github and I'm sure you will find something suitable.
toSet toList
toSet
toList
var ids = [1, 4, 4, 4, 5, 6, 6]; var distinctIds = ids.toSet().toList();
[1, 4, 5, 6]
.
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]
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]
Set , . LinkedHashSet:
Set
LinkedHashSet
import "dart:collection"; void main() { List<String> arr = ["a", "a", "b", "c", "b", "d"]; var 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
, . , .
final list = ['a', 'a', 'b']; final seen = Set<String>(); final unique = list.where((str) => seen.add(str)).toList(); print(unique); // => ['a', 'b']
?
List<T> uniqifyList<T>(List<T> list) { var returnList = List<T>(); for (var item in list) { if (!returnList.contains(item)) { returnList.add(item); } } return returnList; }
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]
2. 3+, , :
final ids = [1, 4, 4, 4, 5, 6, 6]; final distinctIds = [...{...ids}];
Be it more or less readable than ids.toSet().toList(), I will let the reader decide :)
ids.toSet().toList()