Sets in Dart

Sets in Dart#

About#

A Set in Dart is an unordered collection of unique items. Unlike Lists, Sets do not allow duplicate elements, and they are not indexed, meaning you cannot access elements by an index. Sets are particularly useful when you need to ensure that a collection contains only unique elements.

How Sets Work#

  • Sets store unique values, meaning no duplicates are allowed.
  • Because they are unordered, the elements are not stored in any particular order, and the order may change over time.
  • Dart provides the Set class for defining sets. A Set can be created using curly braces {} or the Set() constructor.

Set Types:#

  1. HashSet: The default implementation, where elements are not ordered.
  2. LinkedHashSet: Maintains the order in which elements are added.
  3. SplayTreeSet: Automatically sorts elements.

Usage#

Sets are useful when:

  • You need a collection of unique elements.
  • The order of elements does not matter.
  • Fast membership checking is required.

Common Operations:#

  • Add elements: set.add(value)
  • Remove elements: set.remove(value)
  • Check if element exists: set.contains(value)
  • Set length: set.length

Example#

Example 1: Creating and Using a Set#

void main() {
  // Creating a set of strings
  Set<String> fruits = {'apple', 'banana', 'orange'};
  
  // Adding an element
  fruits.add('mango');
  
  // Trying to add a duplicate element
  fruits.add('apple'); // 'apple' is already in the set, so it won't be added again
  
  // Removing an element
  fruits.remove('banana');
  
  // Checking if an element is in the set
  print(fruits.contains('orange')); // Output: true
  
  // Printing the set
  print(fruits); // Output: {apple, orange, mango}
}

Example 2: Using Set Constructor#

void main() {
  // Creating a set using Set constructor
  Set<int> numbers = Set();
  
  // Adding elements
  numbers.add(1);
  numbers.add(2);
  numbers.add(2); // Duplicate will not be added
  
  // Printing the set
  print(numbers); // Output: {1, 2}
}

Conclusion#

A Set in Dart is an ideal collection when you need to store unique, unordered data. It is particularly useful for scenarios where the uniqueness of elements is important, such as eliminating duplicates from a list or performing fast membership checks.