Home > front end >  Stable list set-difference in Dart
Stable list set-difference in Dart

Time:10-31

We have two lists

List<String> list1 = ['foo', 'bar', 'blah', 'bee', 'fog'];
List<String> list2 = ['bee', 'bar'];

and we'd like to remove from the first the items in the second.

We can iterate, removing those in the second one by one

for (var v in list2) {
  list1.removeWhere((item) => item == v);
}

but that's silly. It'll take time proportional to the product of the length of the two lists.

We can convert to sets and use Dart's Set.difference(), then return a list.

n = (n.toSet().difference(m.toSet())).toList();

but we lose the order of the items in list1.

What's a good way for determining stable list set-difference in Dart?

CodePudding user response:

A solution would be to convert list2 into a Set to make it more efficient to ask if an element from list1 is part of list2. We can then use removeWhere to remove elements from list1:

void main() {
  List<String> list1 = ['foo', 'bar', 'blah', 'bee', 'fog'];
  List<String> list2 = ['bee', 'bar'];
  
  list1.removeWhere(list2.toSet().contains);
  print(list1); // [foo, blah, fog]
}
  •  Tags:  
  • dart
  • Related