Working with Sets in Dart

Sets are a collection of unique items in Dart. Unlike lists, which can contain duplicate elements, sets automatically enforce uniqueness. They are useful when you need to store a collection of items without duplicates and when the order of items is not important.

What Are Sets?

A set in Dart is an unordered collection of unique items. Each item can only appear once in a set, making it an ideal choice for scenarios where you need to ensure that no duplicates are present.

Key Characteristics of Sets:

  • Unique Elements: Sets automatically handle duplicates; if an element is added that already exists, it will not be added again.
  • Unordered: The elements in a set do not have a fixed order, meaning you cannot access them by index.
  • Dynamic Size: Sets can grow or shrink as needed, similar to lists.

Syntax

To create a set in Dart, you can use the following syntax:

Set<type> setName = {element1, element2, element3};

Example

Here’s a simple example of creating and using a set:

void main() {
  Set<String> fruits = {'Apple', 'Banana', 'Cherry', 'Apple'};
  
  print(fruits); // Output: {Apple, Banana, Cherry} 
  }

Use Cases

  • Removing Duplicates: Sets are useful for removing duplicates from a list or other collections.
  • Membership Testing: Sets provide efficient membership testing, making it fast to check if an item is present.
  • Mathematical Operations: Sets can be used to perform mathematical operations like union, intersection, and difference.

Set Manipulations

You can perform various operations on sets, such as adding, removing, and checking for the presence of elements.

Adding Elements

You can use the add() method to insert elements into a set:

void main() {
  Set<String> fruits = {'Apple', 'Banana'};
  fruits.add('Cherry');
  print(fruits); // Output: {Apple, Banana, Cherry} 
  }

Removing Elements

You can remove elements using the remove() method:

void main() {
  Set<String> fruits = {'Apple', 'Banana', 'Cherry'};
  fruits.remove('Banana');
  print(fruits); // Output: {Apple, Cherry} 
  }

Checking Membership

To check if an element is in a set, use the contains() method:

void main() {
  Set<String> fruits = {'Apple', 'Banana', 'Cherry'};
  print(fruits.contains('Banana')); // Output: true   
  print(fruits.contains('Grape'));   // Output: false 
  }

Set Methods

Dart provides several built-in methods to manipulate sets. Here are some important ones:

  • add(element): Adds an element to the set.
  • remove(element): Removes the specified element from the set.
  • contains(element): Checks if the set contains the specified element.
  • clear(): Removes all elements from the set.
  • length: Returns the number of unique elements in the set.
  • union(otherSet): Returns a new set containing elements from both sets.
  • intersection(otherSet): Returns a new set containing elements common to both sets.
  • difference(otherSet): Returns a new set containing elements in the current set but not in the other set.

Example of Set Methods

void main() {
  Set<int> numbers = {1, 2, 3, 4, 5};
  
  numbers.add(6); // Add 6   
  numbers.remove(3); // Remove 3   
  print(numbers); // Output: {1, 2, 4, 5, 6} 
  }

Important Keywords

  • Set: The main data type for creating sets in Dart.
  • var: A keyword that allows you to declare a variable without explicitly specifying its type. Dart infers the type based on the assigned value.
  • final: Used to declare a set that cannot be reassigned, although its contents can be modified.
  • const: Used to declare a compile-time constant set, which means the set cannot be modified at all.

Example of Final and Const Sets

void main() {
  final Set<String> fruits = {'Apple', 'Banana'};
  fruits.add('Cherry'); // Allowed   // fruits = {'Orange'}; // Not allowed, will cause an error 
  const Set<int> numbers = {1, 2, 3};
  // numbers.add(4); // Not allowed, will cause an error }

 

Sets in Dart provide a powerful way to store collections of unique items. They offer efficient membership testing and allow for mathematical operations on collections. Understanding how to create, manipulate, and utilize sets effectively is crucial for developing robust Dart applications.

Sets vs. Lists in Dart

FeatureSetsLists
DuplicatesCannot contain duplicatesCan contain duplicates
OrderUnorderedOrdered
Access MethodCannot access by indexAccessed by index
PerformanceFaster membership testingSlower membership testing
Use CasesUnique collections, membershipOrdered collections, indexing
Availability of MethodsUnion, intersection, differenceConcatenation, slicing, indexing

 

PLAY QUIZ

What is a key characteristic of sets in Dart?

Sets can contain duplicate elements.

Sets are unordered collections of unique items.

Sets have a fixed size after creation.

Sets allow access to elements by index.