i have 3 Lists, for example:
List l1 = [1, 2, 3, 55, 7, 99, 21];
List l2 = [1, 4, 7, 65, 99, 20, 21];
List l3 = [0, 2, 6, 7, 21, 99, 26];
and i expect the common elements:
// [7,99,21]
here is what i've tried but didn't work correctly:
List l1 = [1, 2, 3, 55, 7, 99, 21];
List l2 = [1, 4, 7, 65, 99, 20, 21];
List l3 = [0, 2, 6, 7, 21, 99, 26];
List common = l1;
l2.forEach((element) {
l3.forEach((element2) {
if (!common.contains(element) || !common.contains(element2)) {
common.remove(element);
common.remove(element2);
}
});
});
print(common);
plus, the number of lists is dynamic, so i expect to nest them like this, i have no experience with recursion so i couldn't do it or even know if it's better than nesting loops.
thanks for helping.
You don't need nested loops or recursion for this. Dart has Set
s and a very nice fold
method on Lists
.
main() {
final lists = [
[1, 2, 3, 55, 7, 99, 21],
[1, 4, 7, 65, 99, 20, 21],
[0, 2, 6, 7, 21, 99, 26]
];
final commonElements =
lists.fold<Set>(
lists.first.toSet(),
(a, b) => a.intersection(b.toSet()));
print(commonElements);
}
Gives:
{7, 99, 21}
Further, this can be used no matter how many lists are contained in lists
.
One solution :
void main() {
List l1 = [1, 2, 3, 55, 7, 99, 21];
List l2 = [1, 4, 7, 65, 99, 20, 21];
List l3 = [0, 2, 6, 7, 21, 99, 26];
l1.removeWhere((item) => !l2.contains(item));
l1.removeWhere((item) => !l3.contains(item));
print(l1);
}
Result :
[7, 99, 21]
If your number of lists is dynamic, then a solution is to count all occurences within all the lists, and retains only values where number of occurence is equals to the number of lists :
void main() {
List<List> lists = [
[1, 2, 3, 55, 7, 99, 21],
[1, 4, 7, 65, 99, 20, 21],
[0, 2, 6, 7, 21, 99, 26]
];
Map map = Map();
for (List l in lists) {
l.forEach((item) => map[item] = map.containsKey(item) ? (map[item] + 1) : 1);
}
var commonValues = map.keys.where((key) => map[key] == lists.length);
print(commonValues);
}
Result :
(7, 99, 21)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With