Sets in Dart

A Set is a collection of unique elements - think of it like a bag where you can't have duplicates! If you try to add the same item twice, the set will just ignore the duplicate. Sets are perfect when you need to store a collection of items where uniqueness matters.

Creating Sets

You can create sets in several ways:

// Empty set
var emptySet = <String>{};
Set<int> numbers = {};

// Set with initial values
var fruits = {'apple', 'banana', 'orange'};
Set<String> colors = {'red', 'green', 'blue'};

// Using Set constructor
var animals = Set<String>();
animals.addAll(['cat', 'dog', 'bird']);

Key Properties of Sets

PropertyDescriptionExample
lengthNumber of elements in the setfruits.length
isEmptyReturns true if set is emptyemptySet.isEmpty
isNotEmptyReturns true if set has elementsfruits.isNotEmpty

Adding Elements

var hobbies = <String>{};

// Add single element
hobbies.add('reading');
hobbies.add('swimming');
hobbies.add('reading'); // This won't be added (duplicate!)

print(hobbies); // {reading, swimming}

// Add multiple elements
hobbies.addAll(['cooking', 'dancing', 'reading']);
print(hobbies); // {reading, swimming, cooking, dancing}

Removing Elements

var numbers = {1, 2, 3, 4, 5};

// Remove specific element
numbers.remove(3);
print(numbers); // {1, 2, 4, 5}

// Remove elements that match a condition
numbers.removeWhere((num) => num > 3);
print(numbers); // {1, 2}

// Clear all elements
numbers.clear();
print(numbers); // {}

Checking for Elements

var languages = {'Dart', 'JavaScript', 'Python'};

// Check if element exists
print(languages.contains('Dart')); // true
print(languages.contains('Java')); // false

// Check if any element matches condition
print(languages.any((lang) => lang.startsWith('P'))); // true

// Check if all elements match condition
print(languages.every((lang) => lang.length > 3)); // true

Set Operations

Sets support mathematical operations like union, intersection, and difference:

var setA = {1, 2, 3, 4};
var setB = {3, 4, 5, 6};

// Union (combine both sets)
var union = setA.union(setB);
print(union); // {1, 2, 3, 4, 5, 6}

// Intersection (common elements)
var intersection = setA.intersection(setB);
print(intersection); // {3, 4}

// Difference (elements in setA but not in setB)
var difference = setA.difference(setB);
print(difference); // {1, 2}

Iterating Through Sets

var cities = {'New York', 'London', 'Tokyo', 'Paris'};

// Using for-in loop
for (var city in cities) {
  print('City: $city');
}

// Using forEach method
cities.forEach((city) => print('Visiting $city'));

// Converting to list for indexed access
var cityList = cities.toList();
print('First city: ${cityList[0]}');

When to Use Sets

Sets are ideal when you need to:

  • Store unique values only
  • Perform mathematical set operations
  • Check membership quickly
  • Remove duplicates from a collection

Remember: Sets don't maintain insertion order (except for LinkedHashSet), so if order matters, consider using a List instead!