Question #256EasyGeneral

What is the difference between set vs map and where to use which one provide me with some-example ?

Answer

Overview

text
Set
and
text
Map
are both Dart collection types, but serve very different purposes. Set stores unique values; Map stores key-value pairs.


Set — Unique, Unordered Collection

A

text
Set
holds a collection of unique elements with no duplicates.

dart
// 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
Map
stores associations between unique keys and values.

dart
// 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

FeatureSetMap
StoresUnique valuesKey-value pairs
Duplicates❌ Not allowedKeys must be unique (values can repeat)
AccessBy iteration or contains()By key — O(1)
Use caseUnique collection, fast membership testLookup table, config, JSON
Literal syntax
text
{1, 2, 3}
text
{'key': 'value'}
Empty literal
text
<int>{}
text
{}
or
text
<String,int>{}

⚠️

text
{}
creates an empty Map, not an empty Set! Use
text
<T>{}
for empty Sets.


When to Use Which

Use CaseUse
Remove duplicates from a list
text
Set
Check if item exists (fast)
text
Set
Tag systems, unique IDs
text
Set
JSON-like structured data
text
Map
Lookup by ID/name
text
Map
Counting occurrences
text
Map<String, int>
Caching results
text
Map

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.