user13002252
user13002252

Reputation:

How can I compare 2 Lists<String> and return the difference as a list also?

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

Answers (3)

Mehmet Esen
Mehmet Esen

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

Abion47
Abion47

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

dontberude
dontberude

Reputation: 551

Sure there is:

var solution = a.where((x) => !b.contains(x));

Upvotes: 0

Related Questions