'how can I find a list contains in any element another list in flutter?
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
Solution 1:[1]
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;
}
Solution 2:[2]
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
Solution 3:[3]
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
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | awaik |
Solution 3 | Dmitry Bubnenkov |
Solution 4 | Derek Davidson |