In Dart, a Set is an unordered collection of unique elements. It's a powerful data structure that ensures no duplicates exist within its contents. Sets are particularly useful when you need to store distinct values and perform operations like union, intersection, or difference.
There are multiple ways to create a Set in Dart:
// Using set literals
var fruits = {'apple', 'banana', 'orange'};
// Using the Set constructor
var numbers = Set<int>();
// From an Iterable
var colors = Set.from(['red', 'green', 'blue']);
Dart provides several methods to manipulate sets:
add()
: Add an element to the setremove()
: Remove an element from the setcontains()
: Check if an element exists in the setclear()
: Remove all elements from the set
void main() {
var numbers = {1, 2, 3, 4, 5};
numbers.add(6);
print(numbers); // {1, 2, 3, 4, 5, 6}
numbers.remove(3);
print(numbers); // {1, 2, 4, 5, 6}
print(numbers.contains(4)); // true
numbers.clear();
print(numbers); // {}
}
Dart sets support various operations between multiple sets:
union()
: Combines elements from two setsintersection()
: Returns common elements between setsdifference()
: Returns elements in one set but not in another
void main() {
var set1 = {1, 2, 3, 4};
var set2 = {3, 4, 5, 6};
print(set1.union(set2)); // {1, 2, 3, 4, 5, 6}
print(set1.intersection(set2)); // {3, 4}
print(set1.difference(set2)); // {1, 2}
}
While Sets, Lists, and Maps are all collection types in Dart, they serve different purposes:
Collection | Ordered | Unique Elements | Key-Value Pairs |
---|---|---|---|
Set | No | Yes | No |
List | Yes | No | No |
Map | No | Keys only | Yes |
Choose the appropriate collection type based on your specific needs in your Dart projects.
Dart Sets provide a powerful way to work with unique, unordered collections of elements. They offer efficient operations for managing distinct values and performing set-theoretic operations. By understanding and utilizing Sets effectively, you can write more efficient and cleaner Dart code.
For more advanced collection manipulation, explore Dart Collection Methods to enhance your Dart programming skills.