Collections
Set Operations
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');
}
a ← {red, green, blue}
1void main() {2 var a = {'red', 'green', 'blue'};3 var b = {'green', 'blue', 'yellow'};values this step{red, green, blue}ab ← {green, blue, yellow}
2var a = {'red', 'green', 'blue'};3var b = {'green', 'blue', 'yellow'};4var both = a.intersection(b);values this step{green, blue, yellow}bboth ← {green, blue}
3var b = {'green', 'blue', 'yellow'};4var both = a.intersection(b);5var either = a.union(b);values this step{green, blue}botheither ← {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}eitheronlyA ← {red}
5var either = a.union(b);6var onlyA = a.difference(b);7print('both=$both union=$either');values this step{red}onlyAprint('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}print('only=$onlyA');
7 print('both=$both union=$either');8 print('only=$onlyA');9}outputonly={red}
Compare the Sets
- Set
ahasred,green, andblue. - Set
bhasgreen,blue, andyellow. intersectionkeeps values in both sets.unionkeeps values from either set.differencekeeps values only froma. | 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