Radium Flame
Radium Flame

Reputation: 45

Dart/Flutter - Keep only duplicate items in List

So I'm working on an app in Flutter, and long story short: I have 2 'filter options' which create 2 seperate lists. Now what I want is to use those 2 Lists and find the items which are present in BOTH lists and add that item to a third List.

Example:

List<int> first_list = [1, 2, 3, 4, 5];
List<int> second_list = [1, 2, 8, 9];

Result: [1, 2]

I know I could potentially loop through 1 list and then check with 'contains()' if the item is present in the other list. But it could be that 1 (or both) lists are empty and then my third list will be empty as I simply will never loop to add a duplicate item to the third list

Upvotes: 0

Views: 2016

Answers (3)

Febry Ardiansyah
Febry Ardiansyah

Reputation: 21

You can use intersection

  List<int> firstList = [1, 2, 3, 4, 5];
  List<int> secondList = [1, 2, 8, 9];

  final firsToSet = firstList.toSet();
  final secondToSet = secondList.toSet();

  final res = firsToSet.intersection(secondToSet);
  print(res);

Upvotes: 1

Alex Radzishevsky
Alex Radzishevsky

Reputation: 3768

What you need is intersection between two collections. Most likely it makes sense not to use lists, but rather sets of items.

I would solve this like that:

void main() {
  List<int> first_list = [1, 2, 3, 4, 5];
  List<int> second_list = [1, 2, 8, 9];
  
  final shared = first_list.toSet().intersection(second_list.toSet());
  print(shared);
}

If you can work with sets, not with lists it would be even simpler:

void main() {
  Set<int> first_list = {1, 2, 3, 4, 5};
  Set<int> second_list = {1, 2, 8, 9};
  
  final shared = first_list.intersection(second_list);
  print(shared);
}

Upvotes: 1

julemand101
julemand101

Reputation: 31209

Something like this?

void main() {
  List<int> first_list = [1, 2, 3, 4, 5];
  List<int> second_list = [1, 2, 8, 9];

  final shared = [...first_list.where(second_list.contains)];
  print(shared); // [1, 2]
}

Upvotes: 4

Related Questions