How to create List of common element from two different List in Dart?

Viewed 51

I have Two List.

List<String> A=['1','2','3','4','5'];
List<String> B=['4','5','6','7'];

How to create common element list ?

output

List<String> C=['4','5'];
4 Answers

using .toSet()

List<String> a=['1','2','3','4','5'];
List<String> b=['4','5','6','7'];

List<int> c = a.toSet().where((element) => b.toSet().contains(element)).toList();

You can try

void main() {
  List<String> A=['1','2','3','4','5'];
List<String> B=['4','5','6','7'];

  A.removeWhere((item) => !B.contains(item));

  print(A);
}

Convert List to Set using Set.from then use Set's Set.intersection function like

final characters1 = <String>{'A', 'B', 'C'}; //Set1
final characters2 = <String>{'A', 'E', 'F'}; //Set2 
final unionSet = characters1.intersection(characters2);
print(unionSet); // {A}

then use Set.toList() method on result Set

which list have more length apply loop for that list and check conditon for another list This is the solution

Related