3
var firstList= [1,2,3,4,5];
var secondList= [3,5];

// compare result : 3,5
// return true

var firstList= [1,2,3,4,5];
var secondList= [6,7,8];

// compare result : null
// return false

How can I compare elements the two lists? If there is matching data in the two lists, return true. if there is no match, return false

katre
  • 173
  • 1
  • 5
  • 11

6 Answers6

16

This should help you...

var firstList = [2, 2, 2, 3];
var secondList = [3, 3, 3];

var firstListSet = firstList.toSet();
var secondListSet = secondList.toSet();

print(firstListSet.intersection(secondListSet));
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Josteve
  • 11,459
  • 1
  • 23
  • 35
11

there is plenty of ways to do it, you could use every() and contains() methods to achieve this

this is how I would do it:

  if (secondList.every((item) => firstList.contains(item))) {
    return true;
  } else {
    return false;
  }
Javad Moradi
  • 866
  • 7
  • 18
3

And one more quick way just to check true or false

var firstList = [2, 2, 2, 3];
var secondList = [3, 3, 3];
check(int value) => firstList.contains(value);
bool res = secondList.any(check); // returns true
awaik
  • 10,143
  • 2
  • 44
  • 50
0

Next solution is not perfect, but maybe helpful for someone:

void main() {
  var list = ["aa", "bb", "cc"];
  for (var el in ['abc', 'aaa', 'bb', 'hmbb', 'afg', 'hhcc']) {
    bool isContains = list.any((e) => el.contains(e));
    if(isContains) {
      print(el);
    }
  }
}

Output:

aaa
bb
hmbb
hhcc
Dmitry Bubnenkov
  • 9,415
  • 19
  • 85
  • 145
0

I found this works

bool bTest2 = lstPlayerIDPieceLocationPointID
        .any((element) => lstFoundPoints.contains(element));
    print('bTest2 any..contains: $bTest2');

Always finding if any item in 1 list is also in the other list. I did not care what is was, I just wanted to know if there is a match

0

Function to Test If One List Has Elements of Another List

Just following up on Josteve's answer - this returns a bool as requested in the question rather than a string as Josteve's snippet shows:

void main() {
  
var firstList= [1,2,3,4,5];
var secondList= [3,5];
var thirdList= [9,10];

  
 //There IS an intersection
  
print("Second List: ${isIntersect(secondList, firstList)}");

  //There is NO intersection
  
print("Third List: ${isIntersect(thirdList, firstList)}");
  
}


bool isIntersect(List listOne, List listTwo) {
  return listOne.toSet().intersection(listTwo.toSet()).isNotEmpty;
}

Demo is also on Dart Pad

CoderBlue
  • 695
  • 7
  • 14