Dart Sets in Depth
Two sets can be combined or compared with set operations. Each combining operation returns a new set.
Union, intersection, difference
The three operations compare the same two sets. Each result prints in insertion order, starting from the first set.
void main() {
var a = {1, 2, 3};
var b = {3, 4, 5};
print(a.union(b));
print(a.intersection(b));
print(a.difference(b));
print(b.difference(a));
}Test a whole group with containsAll
containsAll checks every element of the smaller set at once. One missing element makes the whole test false.
void main() {
var colors = {'red', 'green', 'blue', 'pink'};
print(colors.containsAll({'red', 'blue'}));
print(colors.containsAll({'red', 'gold'}));
}Remove duplicates through a set
The list passes through a set, which keeps each value once. The list built back from the set holds four values instead of six.
void main() {
var numbers = [3, 1, 3, 2, 1, 4];
var unique = numbers.toSet().toList();
print(unique);
print(numbers.length);
print(unique.length);
}A set as a membership test
Each guest name is tested against the allowed set. The test answers true or false for one name at a time.
void main() {
var allowed = {'ana', 'ben', 'cid'};
var guests = ['ana', 'zoe', 'ben'];
for (var guest in guests) {
print('$guest: ${allowed.contains(guest)}');
}
}Example
void main() {
var morning = {'yoga', 'run', 'swim'};
var evening = {'run', 'walk', 'swim'};
var both = morning.intersection(evening);
var onlyMorning = morning.difference(evening);
print(both);
print(onlyMorning);
print(morning.union(evening).length);
}Key points
- union returns a set holding every element from both sets.
- intersection returns a set holding only the elements found in both sets.
- difference returns the elements of the first set that the second set lacks.
- containsAll reports whether every element of another set is present.
- Passing a list through a set and back removes its duplicates.
- A set answers a membership test quickly, even when it holds many elements.
In this example, the intersection holds the activities found in both sets. The difference holds the one activity found only in the morning set. The union holds four activities in total.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
Set a holds {1, 2, 3} and set b holds {3, 4}. What is a.difference(b)?