What is a Set in Dart?
A Set
in Dart is an unordered collection of unique items. Sets are useful when you want to store distinct values and ensure that no duplicates are present. Unlike lists, which maintain the order of elements and allow duplicates, sets focus on the uniqueness of their elements.
1. Characteristics of a Set
- Unordered: The elements in a set do not have a specific order. When you iterate over a set, the order of elements may vary.
- Unique Elements: A set automatically removes duplicate values. If you try to add a duplicate element, it will not be added.
- Efficient Lookups: Sets provide efficient methods for checking the existence of an element, making them suitable for membership tests.
2. Creating a Set
You can create a set in Dart using the Set
literal or the Set
constructor.
Example of Creating a Set
void main() {
// Creating a set using a set literal
Set<string> fruits = {'apple', 'banana', 'orange'};
// Adding an element
fruits.add('grape');
// Trying to add a duplicate element
fruits.add('apple'); // This will not be added
// Iterating through the set
for (var fruit in fruits) {
print(fruit); // Output: apple banana orange grape (order may vary)
}
}
</string>
In this example, we create a set of strings representing fruits. We add a new fruit and attempt to add a duplicate. The duplicate is not added, and we iterate through the set to print its contents.
3. Differences Between Set and List
Feature | Set | List |
---|---|---|
Order | Unordered | Ordered |
Duplicates | No duplicates allowed | Duplicates allowed |
Access | Accessed by value | Accessed by index |
Performance | Faster lookups for existence | Slower lookups for existence |
4. Example of Using a Set vs. a List
void main() {
// Creating a list with duplicates
List<string> fruitList = ['apple', 'banana', 'apple', 'orange'];
// Creating a set from the list
Set<string> fruitSet = Set.from(fruitList);
print('List: $fruitList'); // Output: List: [apple, banana, apple, orange]
print('Set: $fruitSet'); // Output: Set: {apple, banana, orange}
}
</string></string>
In this example, we create a list of fruits that contains duplicates. We then create a set from the list, which automatically removes the duplicates. The output shows the original list and the resulting set.
5. Conclusion
Sets in Dart are a powerful collection type that allows you to store unique items without duplicates. They differ from lists in terms of order, duplication, and access methods. Understanding when to use a set versus a list is essential for effective data management in Dart applications.