Flutter - How to find non-common elements in list with for loop?

Viewed 88
List a = [3,5,7,8,14,32];
List b = [5,6,11,14,18,32,47];

I want to print [3,6,7,8,11,18,47]

3 Answers
List a = [3,5,7,8,14,32];
List a2 = [3,5,7,8,14,32];
List b = [5,6,11,14,18,32,47];
  
a.removeWhere((e) => b.any((item) => e == item)); // [3, 7, 8]
b.removeWhere((e) => a2.any((item) => e == item)); // [6, 11, 18, 47]

List result = a + b;
result.sort((alpha, beta) => alpha - beta); // [3, 6, 7, 8, 11, 18, 47]

List<int> getNonCommonList(List<int> a, List<int> b) {
  List<int> result = [];
  for (int e in a) {
    if (!b.contains(e)) {
      result.add(e);
    }
  }
  for (int e in b) {
    if (!a.contains(e)) {
      result.add(e);
    }
  }
  result.sort();
  return result;
}

List<int> a = [3,5,7,8,14,32];
List<int> b = [5,6,11,14,18,32,47];
getNonCommonList(a, b);

Don't fall into the trap of the XY problem by asking about a particular solution (in your case, using a for loop).

If you don't actually need to use a for loop, I'd just use Sets and compute the set difference of the intersection from the union:

void main() {
  var a = [3, 5, 7, 8, 14, 32];
  var b = [5, 6, 11, 14, 18, 32, 47];

  var aSet = a.toSet();
  var bSet = b.toSet();

  var nonCommonSet = aSet.union(bSet).difference(aSet.intersection(bSet));
  var nonCommonList = nonCommonSet.toList()..sort();
  print(nonCommonList); // Prints: [3, 6, 7, 8, 11, 18, 47]
}

It would be even simpler if you can use Sets everywhere instead of Lists.

Related