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?

Raduan Santos
  • 1,023
  • 1
  • 21
  • 45
lamatat
  • 503
  • 1
  • 10
  • 21

3 Answers3

19

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
}
Albert221
  • 5,223
  • 5
  • 25
  • 41
9

Set has an intersection that does that:

list1.toSet().intersection(list2.toSet()).length > 0
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • https://stackoverflow.com/questions/10404516/how-can-i-compare-lists-for-equality-in-dart mentions some other handy features to compare lists or iterables (not directly related to the question though) – Günter Zöchbauer Jan 28 '19 at 12:22
  • 2
    Instead of converting both to sets, you can als just do `list1.any(list2.toSet().contains)`. – lrn Jan 29 '19 at 06:37
0

A shorter version:

bool hasCommonElement = list1.any(list2.contains);
iDecode
  • 22,623
  • 19
  • 99
  • 186