Reputation:
I'm a beginner in Dart. I have 2 lists.
List<String> a = ['John','Ella','Kattie'];
List<String> b = ['Ella'];
Is there any method to be called that returns me a
List<String> c = ['John','Kattie'];
?
I checked the docs but I couldn't find something, maybe I was not paying too much attention. I was trying to hard code this
for(String i in a)
{
for(String j in b) {
if(i != j) {
c.add(i);
}
}
}
But I'm sure there's another way to do that!
Can you help me please? Thank you in advance!
Upvotes: 0
Views: 50
Reputation: 6876
If you don't mind using Set
(I think you wouldn't for this specific case), there is built-in method from Set
class called difference
that exactly gives difference of two sets.
final a = <String>{'John','Ella','Kattie'};
final b = <String>{'Ella'};
main(){
print(a.difference(b));
}
Upvotes: 2
Reputation: 24681
This is known as a difference function. You can do it the way you are already doing, but it's obviously not ideal since you have to loop over every element in b
for every element in a
, giving it a complexity of O(m * n)
. There's also the where(contains)
approach which is far more compact, but ultimately does the same thing.
The most performant way to do it is to convert the second list into a set and compare it that way:
final bSet = Set.from(b);
final c = [];
for (var x in a) {
if (!bSet.contains(x)) {
c.add(x);
}
}
Now that the second list is a set, contains
lookups are constant time, so the only complex step is the conversion to a step. Now that you are looping over both lists only one time each, giving a complexity of O(m + n)
.
Upvotes: 0