Dart Sets
A set is a collection that holds each value only once. Adding a value that is already there changes nothing.
Duplicates drop out
The literal lists red twice, and the set keeps it once. The length counts 2, not 3.
void main() {
var colors = <String>{'red', 'blue', 'red'};
print(colors);
print(colors.length);
}A set built from a list
toSet turns the list into a set and the second 3 drops out. The order of the first sightings stays.
void main() {
var nums = [3, 1, 3, 2];
var unique = nums.toSet();
print(unique);
}Adding and checking values
add puts sale in and the second add of new changes nothing. contains answers true for sale and false for old.
void main() {
var tags = <String>{'new'};
tags.add('sale');
tags.add('new');
print(tags);
print(tags.contains('sale'));
print(tags.contains('old'));
}Example
void main() {
var scores = [10, 20, 10, 30, 20];
var unique = scores.toSet();
print(unique);
print(unique.length);
unique.add(40);
print(unique.contains(40));
}Key points
- A set holds each value only once.
- Use Set with a kind in angle brackets to build a set of that kind.
- Use toSet on a list to turn the list into a set.
- Use add to put a new value into a set.
- Use contains to check whether a set holds a value.
- The length of a set counts each stored value once.
In this example, the list holds five numbers with 10 and 20 repeated. toSet keeps each number once, so the print shows three values. The length print shows 3. add puts 40 into the set. The last print shows true because contains finds 40.
Note
Print shows a set with curly braces, in the order values were first added.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
How many values does the set <int>{4, 4, 5} hold?