Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing two string lists and check if they have at least one same string

Tags:

flutter

dart

I'm trying to compare two String list with each other and check if at least the have one exact same string or not ..

For example:

List<String> list1 = ['1','2','3','4'];

List<String> list2 = ['1','5','6','7'];

In this case I will do action cause both have same string which is 1, and it could be more than one exact same string and the action will be the same.

But if they don't have any similar strings then I will do another action.

How can I do something like this?

like image 705
lamatat Avatar asked Jan 28 '19 12:01

lamatat


People also ask

How do I compare two lists of strings?

Use sort() method and == operator to compare lists The sorted list and the == operator are used to compare the list, element by element.

How do you check if two lists have the same values?

Use == operator to check if two lists are exactly equal It is the easiest and quickest way to check if both the lists are exactly equal.

Can you compare lists with ==?

We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.


2 Answers

You can do it with any() and contains() method:

if (list1.any((item) => list2.contains(item))) {
    // Lists have at least one common element
} else {
    // Lists DON'T have any common element
}
like image 198
Albert221 Avatar answered Oct 04 '22 12:10

Albert221


Set has an intersection that does that:

list1.toSet().intersection(list2.toSet()).length > 0
like image 26
Günter Zöchbauer Avatar answered Oct 04 '22 12:10

Günter Zöchbauer