What is the difference between set vs map and where to use which one provide me with some-example ?
Answer
Overview
and textSet are both Dart collection types, but serve very different purposes. Set stores unique values; Map stores key-value pairs.textMap
Set — Unique, Unordered Collection
A
text
Setdart// Creating a Set final fruits = {'apple', 'banana', 'orange'}; final numbers = <int>{1, 2, 3, 4, 5}; final empty = <String>{}; // Adding elements fruits.add('grape'); // Adds fruits.add('apple'); // ❌ Duplicate — ignored silently print(fruits); // {apple, banana, orange, grape} // Checking membership — O(1) print(fruits.contains('apple')); // true print(fruits.contains('mango')); // false // Set operations final a = {1, 2, 3, 4}; final b = {3, 4, 5, 6}; print(a.union(b)); // {1, 2, 3, 4, 5, 6} print(a.intersection(b)); // {3, 4} print(a.difference(b)); // {1, 2}
Map — Key-Value Pairs
A
text
Mapdart// Creating a Map final person = {'name': 'Alice', 'age': '28', 'city': 'Mumbai'}; final scores = <String, int>{'Math': 95, 'Science': 88}; // Access by key — O(1) print(person['name']); // Alice print(scores['Math']); // 95 // Add / Update scores['English'] = 92; // Add new key scores['Math'] = 98; // Update existing // Check key/value existence print(scores.containsKey('Math')); // true print(scores.containsValue(88)); // true // Iterate scores.forEach((key, value) => print('$key: $value')); // Null safety print(scores['Art'] ?? 0); // 0 (key doesn't exist)
Key Differences
| Feature | Set | Map |
|---|---|---|
| Stores | Unique values | Key-value pairs |
| Duplicates | ❌ Not allowed | Keys must be unique (values can repeat) |
| Access | By iteration or contains() | By key — O(1) |
| Use case | Unique collection, fast membership test | Lookup table, config, JSON |
| Literal syntax | text | text |
| Empty literal | text | text text |
⚠️
creates an empty Map, not an empty Set! Usetext{}for empty Sets.text<T>{}
When to Use Which
| Use Case | Use |
|---|---|
| Remove duplicates from a list | text |
| Check if item exists (fast) | text |
| Tag systems, unique IDs | text |
| JSON-like structured data | text |
| Lookup by ID/name | text |
| Counting occurrences | text |
| Caching results | text |
Practical Examples
dart// Set — remove duplicates from list final list = [1, 2, 2, 3, 3, 4]; final unique = list.toSet().toList(); // [1, 2, 3, 4] // Map — word count final words = ['apple', 'banana', 'apple', 'cherry']; final count = <String, int>{}; for (final w in words) { count[w] = (count[w] ?? 0) + 1; } print(count); // {apple: 2, banana: 1, cherry: 1}
Quick Rule: Need unique items? → Set. Need key-value lookup? → Map.