Sets and Maps in Dart
Sets and Maps are two important data structures in programming. Dart has support for both of them. Sets are unordered collections of unique items. Maps are collections of key-value pairs. Maps can be compared to json objects.
Sets
Sets are unordered collections of unique items. Dart provides the Set class for this purpose.
Syntax of sets in dart
final variable_name = <type>{};
Example
void main() {
var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};
var names = <String>{};
Set<String> names = {}; // This works, too.
}
To create a set that’s compile-time constant, add const before the set literal:
final constantSet = const {
'fluorine',
'chlorine',
'bromine',
'iodine',
'astatine',
};
You can’t change a constant set.
void main() {
var elements = <String>{};
elements.add('fluorine');
elements.addAll(halogens);
print(elements.length);
}
Output
5
Methods
void main() {
var elements = <String>{};
elements.add('fluorine');
elements.addAll(halogens);
print(elements.length);
elements.remove('fluorine');
print(elements.contains('fluorine'));
print(elements.isEmpty);
print(elements.isNotEmpty);
print(elements.first);
print(elements.last);
print(elements);
}
Output
5
false
false
true
chlorine
astatine
{chlorine, bromine, iodine, astatine}
Maps
A map is an object that associates keys and values. Both keys and values can be any type of object. Each key occurs only once, but you can use the same value multiple times.
Syntax
final variable_name = <key_type, value_type>{};
Example
void main() {
var gifts = {
// Key: Value
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
var nobleGases = {
2: 'helium',
10: 'neon',
18: 'argon',
};
}
Methods
void main() {
var gifts = {
// Key: Value
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
var nobleGases = {
2: 'helium',
10: 'neon',
18: 'argon',
};
print(gifts.length);
print(gifts['first']);
print(gifts['fifth']);
print(gifts[1]);
print(gifts.containsKey('first'));
print(gifts.containsValue('partridge'));
gifts.update('first', (value) => 'pear');
print(gifts['first']);
gifts.remove('second');
print(gifts);
gifts.forEach((key, value) {
print(key);
print(value);
});
}
Output
3
partridge
golden rings
null
true
true
pear
{first: pear, fifth: golden rings}
first
pear
fifth
golden rings
Conclusion
In this tutorial, we learned about sets and maps in dart. We learned how to create sets and maps in dart. We also learned about the methods of sets and maps.