Kinda Code
Home/Dart/Dart: 2 Ways to Find Common Elements of 2 Lists

Dart: 2 Ways to Find Common Elements of 2 Lists

Last updated: September 15, 2023

Common (mutual) elements of two lists are the values or items that exist in both lists, appearing in each list at least once. These elements are shared or overlapping between the two lists. This succinct, example-based article will walk you through some different ways to find common elements of two given lists in Dart (and Flutter as well). Let’s begin!

Using Set operations

This solution uses the built-in Set class in Dart, which provides methods for performing set operations such as intersection, union, difference, etc.

The steps:

  1. Convert the two lists into sets using the toSet() method.
  2. Use the intersection() method on one of the sets and pass the other set as an argument. This will return a new set that contains the elements that are common to both sets.
  3. Convert the resulting set back to a list using the toList() method.

Code example:

// KindaCode.com
// main.dart
import 'package:flutter/foundation.dart' show kDebugMode;

void main() {
  // Define two lists
  List<int> list1 = [1, 2, 3, 4, 5];
  List<int> list2 = [3, 4, 5, 6, 7];

  // Convert the lists to sets
  Set<int> set1 = list1.toSet();
  Set<int> set2 = list2.toSet();

  // Find the intersection of the sets
  Set<int> common = set1.intersection(set2);

  // Convert the set to a list
  List<int> result = common.toList();

  // Print the result
  if (kDebugMode) {
    print(result);
  }
}

Output:

[3, 4, 5]

This approach is simple, concise, and easy to implement.

Using a temporary map

This approach uses a temporary map to store the frequency of each element in one of the lists and then iterates over the other list to check if any element matches with the keys in the map. The detailed instruction is as follows:

  1. Create an empty map using the Map() constructor or the {} literal syntax.
  2. Loop through one of the lists and for each element, increment its value in the map by one. If the element does not exist in the map, initialize its value to one.
  3. Create an empty list to store the result.
  4. Loop through the other list and for each element, check if it exists as a key in the map. If yes, append it to the result list and set its value in the map to zero. This will ensure that duplicate elements are not added to the result list more than once.
  5. Return or print the result list.

Complete example:

// KindaCode.com
// main.dart
import 'package:flutter/foundation.dart' show kDebugMode;

void main() {
  // Define two lists
  List list1 = ['A', 'B', 'C', 'D', 'E', 'E', 'C'];
  List list2 = ['C', 'D', 'E', 'F', 'G', 'C', 'D'];

  // Create an empty map
  Map<String, int> map = {};

  // Loop through list1 and update the map
  for (var s in list1) {
    if (map.containsKey(s)) {
      // we use ! to deal with null safety
      map[s] = map[s]! + 1;
    } else {
      map[s] = 1;
    }
  }

  // Create an empty list for result
  List result = [];

  // Loop through list2 and check for common elements
  for (var s in list2) {
    if (map.containsKey(s)) {
      // Add the element to the result list only if it's not already there
      if (map[s]! > 0) {
        result.add(s);
        map[s] = 0;
      }
    }
  }

  // Print or return the result
  if (kDebugMode) {
    print(result);
  }
}

Output:

[C, D, E]

This approach is a little bit more verbose than the first one, but it gives you more flexibility to customize the logic.

Conclusion

You’ve learned more than one technique to get a list of mutual elements from two other given lists. If you’d like to explore more new and exciting about modern Flutter and Dart, take a look at the following articles:

You can also tour around our Flutter topic page or Dart topic page for the most recent tutorials and examples.

Related Articles