Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete duplicates in a Dart List? list.distinct()?

Tags:

list

dart

How do I delete duplicates from a list without fooling around 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 

Set seems to be way faster!! But it loses the order of the items :/

like image 956
Gero Avatar asked Aug 19 '12 22:08

Gero


1 Answers

Use toSet and then toList

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

Result: [1, 4, 5, 6]

Or with spread operators:

var distinctIds = [...{...ids}]; 
like image 83
atreeon Avatar answered Oct 07 '22 01:10

atreeon