Dart Sets

Learn via video courses
Topics Covered

Overview

Dart Sets are unordered collections of unique elements in Dart programming language. They provide a way to store and manage distinct values without duplication. Sets use a hash-based mechanism for efficient element access, insertion, and removal. Unlike lists, they do not have indexes, and their elements are not accessed by position. Dart Sets are useful for removing duplicates from lists, performing mathematical operations like union, intersection, and difference, and optimizing lookup operations when order is not critical.

Functions Involving Sets

FunctionDescription
variable_name.elementAt(index);It retrieves the element at the specified index in a set. However, sets are unordered collections, so there is no inherent index-based order. The returned output type depends on the set's defined element type. Use this function carefully, considering that the order of elements in sets can vary, and indexing may not provide consistent results.
variable_name.remove(element_name);It is used to remove the element_name from the set referenced by variable_name. If the specified element_name exists in the set, it will be deleted or removed from the set. If the element_name is not found in the set, the set remains unchanged. This function provides a convenient way to eliminate a specific element from the set based on its value, ensuring that the set remains free of duplicates or unwanted elements.
variable_name.length;It returns the number of elements in the set. It provides the size or count of elements present in the set. The output of this expression is an integer, representing the total number of elements in the set.
variable_name.contains(element_name);It checks whether the element_name exists in the set referenced by variable_name. If the element_name is present in the set, the function returns true, indicating that the element is found. Otherwise, it returns false, indicating that the element is not present in the set. This function is useful for verifying the presence of a specific element in a set before performing further operations on it.
variable_name.forEach(…);It is used to perform a specified operation or command for each element present in the set referenced by variable_name. It iterates through all the elements in the set and executes the provided command or function for each element. This enables you to apply the same logic or action to every element in the set without having to write explicit loops.
variable_name.clear();It is used to empty the set referenced by variable_name, removing all elements and making it an empty set. This function is helpful when you want to reset the set or discard its existing data, providing a convenient way to start afresh with an empty set, ready to hold new elements.
variable_name.remove(element_name);It is used to remove an element from the set referenced by variable_name. The element_name provided as an argument to the remove function is the value of the element that you want to delete from the set. If the element_name is found in the set, it will be removed from the set. If the element_name is not present in the set, the set remains unchanged. This function is useful for selectively removing specific elements from the set based on their values, ensuring that the set only contains the desired elements.

Dart Initializing Set

Initializing a set in Dart can be achieved using several methods, each with its own advantages and use cases. Sets are defined by the 'Set' class in Dart's core library, and you can use literals or constructors to create and initialize sets. Let's explore these methods in detail.

  1. Using Set Literals:

    Dart allows you to create sets using set literals. Set literals are denoted by curly braces {} and can be initialized with a list of unique elements.

    Code:

    Output:

  2. Using the Set Constructor:

    Dart provides a constructor for the 'Set' class, which allows you to initialize a set using an iterable like a list.

    Output:

  3. Empty Set Initialization:

    You can also create an empty set and add elements to it later using the set literal syntax or the set constructor without providing any initial values.

    Output:

  4. Using the 'Set.from' constructor with a Function:

    You can create a set from an iterable using the 'Set.from' constructor and a function that returns the elements to be added to the set.

    Output:

Remember that sets only contain unique elements, so if you try to add duplicate elements to a set, they will be ignored. Sets are mutable, meaning you can add or remove elements after initialization. Additionally, Dart's sets do not guarantee the order of elements.

Adding Element into Set

Adding an element into a set in Dart is a straightforward process. Dart sets are mutable, which means you can modify them after initialization. To add an element to a set, you can use the add() method provided by the Set class. Here's a brief explanation of how to add an element to a set in Dart:

Output:

In the example above, we create a set named mySet containing three fruits: 'apple', 'orange', and 'banana'. Then, using the add() method, we add the element 'grape' to the set, and the set is updated to include this new element.

Note:

It's important to note that if you try to add an element that already exists in the set, it won't create duplicates. Sets only store unique elements, so adding an element that's already present in the set will have no effect. The element will not be added again, and the set will remain unchanged.

Adding elements to sets is a common operation when working with collections in Dart, especially when you want to maintain a collection of unique elements and ensure there are no duplicates.

Accessing the Elements in Set

In Dart, accessing elements in a set can be done using iteration or by checking for the existence of a specific element. Since sets are unordered collections, there is no direct index-based access as in lists or arrays. Here are the main ways to access elements in a set:

  1. Using Iteration:

    You can use iteration, such as a for-in loop or the forEach() method, to access each element in the set.

    Output:

  2. Checking for Element Existence:

    To check if a specific element exists in a set, you can use the contains() method, which returns a boolean value indicating whether the element is present or not.

    Output:

Note:

Remember that sets are best suited for maintaining collections of unique elements and performing set-specific operations. Indexed access to elements is not a primary use case for sets, as they don't preserve element order. If you need indexed access, you may consider converting the set to a list using the toList() method, but be aware that the order in the list may not be the same as in the original set.

Finding Element in a Set in Dart

In Dart, a set is an unordered collection of unique elements. To find an element in a set, you can use the contains() method. This method checks if the set contains a specific element and returns a boolean value indicating the result.

Here's a brief example of how to use the contains() method in Dart:

Output:

Remove Elements from Set in Dart

  1. Using remove() method:

    The remove() method removes a specific element from the set if it exists. If the element is found and successfully removed, the method returns true. If the element is not found in the set, the method returns false.

    Output:

  2. Using removeAll() method:

    The removeAll() method allows you to remove all elements from the set that are present in another iterable (e.g., another set, list, or iterable). This method modifies the original set by removing all the common elements.

    Output:

    In this example, the removeAll() method removed the elements 3 and 4 from set1 since they were also present in set2.

Note:

Keep in mind that the remove() method only removes one occurrence of the specified element, even if there are multiple occurrences in the set. To remove all occurrences, you need to call the remove() method repeatedly or use other methods like removeWhere() with a custom condition.

TypeCast Set to List

In Dart, you can convert a Set to a List using the toList() method. The toList() method is available for most collection types, including Set. It creates a new List containing all the elements from the Set in the order they were inserted.

Here's an example of how to do it:

Output:

Note:

Keep in mind that since a List can have duplicate elements, if the original Set contained duplicates, they would still be present in the resulting List. If you want to remove duplicates from the List, you can use the toSet() method, which converts a List to a Set, effectively removing any duplicates.

Operations on Set in dart

In Dart, you can perform various set operations on collections using the built-in Set class. The Set class provides methods to perform common set operations, such as union, intersection, difference, and more. Here's a brief overview of some commonly used set operations in Dart:

  1. Union (union):

    The union of two sets contains all elements from both sets, without any duplicates.

    Output:

  2. Intersection (intersection):

    The intersection of two sets contains only the elements that are present in both sets.

    Output:

  3. Difference (difference):

    The difference of two sets contains elements that are present in the first set but not in the second set.

    Output:

  4. Subset (containsAll):

    You can check if one set is a subset of another set using the containsAll method.

    Output:

In these examples, we use the Set class methods union, intersection, and difference to perform the corresponding set operations. For the subset operation, we use the every method to check if all elements in set2 are present in set1.

Properties of Set in Dart

PropertyDescription
UniquenessA set cannot contain duplicate elements. If you try to add an element that already exists in the set, it will be ignored.
UnorderedSets do not maintain the order of elements. The order of insertion is not preserved, and there is no way to access elements by index.
MutableSets are mutable, meaning you can add or remove elements after the set is created.
SizeSets automatically adjust their size to accommodate new elements. The size of a set can grow or shrink dynamically as elements are added or removed.
Type SafetyDart sets can only contain elements of a single specified type. You can use generics to specify the type of elements a set can hold.
EqualitySets in Dart are considered equal if they have the same elements, regardless of their order.

Conclusion

  • Sets in Dart offer a collection of unique elements, ensuring no duplicates are present, and making them efficient for handling distinct data.
  • Dart's Set class provides various methods for manipulating sets, such as adding, removing, and checking for the existence of elements, enhancing data management capabilities.
  • With constant time complexity for basic operations like insertion, deletion, and membership testing, sets are suitable for optimizing performance in applications that require frequent data modifications.
  • Sets can be easily converted to lists and vice versa, allowing for seamless integration with other data structures and simplifying data processing tasks.
  • When solving problems related to eliminating duplicates or finding common elements between multiple collections, sets become invaluable due to their inherent uniqueness property.
  • Dart sets offer developers a valuable tool for managing distinct data efficiently and performing various operations on unique elements with ease.