Dart Set exposes the classic set-algebra methods on top of plain membership. a.intersection(b) is the set of values present in both, a.union(b) is everything in either, and a.difference(b) is everything in a that is not in b. Each call returns a fresh Set; a and b are not modified. The result preserves insertion order from a, with new values from b appearing after for union.

Program

Play the program to compute the intersection, union, and difference of two color sets and print all three.

set_operations.dart
Replay: real traced execution (multi-file project)
void main() {
  var a = {'red', 'green', 'blue'};
  var b = {'green', 'blue', 'yellow'};
  var both = a.intersection(b);
  var either = a.union(b);
  var onlyA = a.difference(b);
  print('both=$both union=$either');
  print('only=$onlyA');
}
  1. a ← {red, green, blue}

    1void main() {2  var a = {'red', 'green', 'blue'};3  var b = {'green', 'blue', 'yellow'};
    values this step{red, green, blue}a
  2. b ← {green, blue, yellow}

    2var a = {'red', 'green', 'blue'};3var b = {'green', 'blue', 'yellow'};4var both = a.intersection(b);
    values this step{green, blue, yellow}b
  3. both ← {green, blue}

    3var b = {'green', 'blue', 'yellow'};4var both = a.intersection(b);5var either = a.union(b);
    values this step{green, blue}both
  4. either ← {red, green, blue, yellow}

    4var both = a.intersection(b);5var either = a.union(b);6var onlyA = a.difference(b);
    values this step{red, green, blue, yellow}either
  5. onlyA ← {red}

    5var either = a.union(b);6var onlyA = a.difference(b);7print('both=$both union=$either');
    values this step{red}onlyA
  6. print('both=$both union=$either');

    6var onlyA = a.difference(b);7print('both=$both union=$either');8print('only=$onlyA');
    outputboth={green, blue} union={red, green, blue, yellow}
  7. print('only=$onlyA');

    7  print('both=$both union=$either');8  print('only=$onlyA');9}
    outputonly={red}

Compare the Sets

  1. Set a has red, green, and blue.
  2. Set b has green, blue, and yellow.
  3. intersection keeps values in both sets.
  4. union keeps values from either set.
  5. difference keeps values only from a. | Operation | Result | | --- | --- | | a.intersection(b) | {green, blue} | | a.union(b) | {red, green, blue, yellow} | | a.difference(b) | {red} |
intersection `a.intersection(b)` is the set of values present in both `a` and `b`. Neither input is modified; a fresh `Set` is returned.
union `a.union(b)` is the set of every value in `a` or `b`. Values from `a` come first in insertion order, with any new values from `b` appended.
difference `a.difference(b)` is the set of values in `a` that are not in `b`. Use it to drop a set of unwanted entries from another set.

Exercise: set_operations.dart

Compute intersection, union, and difference for two color sets and print each result