Operations on a Set | Dart Set Extensions | Dart Set 
 Methods

Operations on a Set | Dart Set Extensions | Dart Set Methods

Operations on a Set:

Set operation like union , intersection , and difference.

  • Union: Combining two sets into one set containing all elements from both sets. Use the union() method or the | operator.

Example

void main() {
  // Define two sets
  Set<int> set1 = {1, 2, 3, 4};
  Set<int> set2 = {3, 4, 5, 6};

  // Perform union using the union() method
  Set<int> unionSet = set1.union(set2);
  print("Union of set1 and set2: $unionSet");
}

Output

Union of set1 and set2: {1, 2, 3, 4, 5, 6}

Exited.
  • Intersection: Finding the common elements between two sets. Use the intersection() method or the & operator.

Example

void main()
{
     Set<int> set1 = {1, 2, 3, 4};
     Set<int> set2 = {3, 4, 5, 6};


     Set<int> intersection = set1.intersection(set2);
     print("intersection of set1 and set2 : $intersection ");

}

Output

intersection of set1 and set2 : {3, 4}
  • Difference: Finding the elements that are in one set but not in another. Use the difference() method or the - operator.

Example

void main()
{
      Set<int> set1 = {1, 2, 3, 4};
      Set<int> set2 = {3, 4, 5, 6};

      Set<int> Difference = set1.difference(set2);
      print("differnce set1 and set2 : $Difference");
      print("differnce set1 and set2 : $Difference");
}

Output

difference set1 and set2 :{1, 2}
differnce set1 and set2 : {1, 2}

Dart set Extension

  • To additional set Extension for sets in the dart:core library.

Dart Set Method

  • They provide a flexible way to work with collections of unique elements.

  • containsAll()

  • addAll()

  • clear()

  • isEmpty()

Example

 bool coontained = set1.containsAll([6, 7]);
  set1.addAll([7, 8]);
  set1.clear();
  bool empty = set1.isEmpty;
  print(coontained);