8

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?

1
  • @MatthewPage of course i know! but this doesn't work with looping :) Commented Jan 28, 2019 at 12:22

3 Answers 3

20

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much!
@lamatat if you found an answer helpful and it resolves your issue, please accept the answer :)
both answers are helpful and working and answered the same time .. i don't know to accept which so i uovoted both lol
9

Set has an intersection that does that:

list1.toSet().intersection(list2.toSet()).length > 0

2 Comments

stackoverflow.com/questions/10404516/… mentions some other handy features to compare lists or iterables (not directly related to the question though)
Instead of converting both to sets, you can als just do list1.any(list2.toSet().contains).
0

A shorter version:

bool hasCommonElement = list1.any(list2.contains);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.