In Dart, a Set is an unordered collection of unique elements. Unlike a List, a Set does not allow duplicate values, making it ideal for scenarios where uniqueness is required, such as tags, IDs, or items in a collection where order is irrelevant.
In Dart, a Set is an unordered collection of unique elements. This means that a Set cannot contain duplicate values. Sets are useful when you need to store a collection of items where the order doesn't matter and you want to ensure that each item appears only once.
Here's a breakdown of Sets in Dart:
Type Declaration:
You can specify the type of elements the set will store (e.g., Set<int>, Set<String>).
If no type is specified, the set will default to Set<dynamic>.
Set Literal:
Sets are created using curly braces {}.
Set Constructor:
Dart provides constructors like Set(), Set.from(), Set.of(), and Set.unmodifiable() for creating sets programmatically.
1. Creating Sets
Using Set literals: The most common way to create a set is using curly braces {}:
var numbers = {1, 2, 3, 4, 5}; // Set of integers
var fruits = {'apple', 'banana', 'orange'}; // Set of strings
var mixed = {1, 'hello', true}; // Set of mixed data types
Using the Set constructor: You can also create a set using the Set constructor:
var numbers = <int>{}; // Creates an empty set of integers
var moreNumbers = Set<int>(); // Another way to create an empty set of integers
var fromList = Set.from([1, 2, 2, 3, 3, 3]); // Creates a set from a list, removing duplicates
2. Key Characteristics of Sets
Unordered: Elements in a set do not have a specific order. When you iterate through a set, the order of elements is not guaranteed.
Unique elements: Sets automatically remove duplicate values. If you try to add a value that already exists in the set, it will be ignored.
3. Set Properties and Methods
Dart provides several methods to work with sets:
length: Returns the number of elements in the set.
add(element): Adds an element to the set.
addAll(iterable): Adds all elements from an iterable to the set.
remove(element): Removes an element from the set.
contains(element): Checks if the set contains a specific element.
union(otherSet): Returns a new set containing all elements from both sets.
intersection(otherSet): Returns a new set containing only the elements that are present in both sets.
difference(otherSet): Returns a new set containing the elements that are in the first set but not in the second set.
forEach(action): Executes a function for each element in the set.
clear(): Removes all elements from the set.
When to use Sets:
Removing duplicates: If you have a collection of items and need to ensure uniqueness.
Membership testing: Quickly checking if an element exists in a collection.
Mathematical set operations: Performing union, intersection, and difference operations.
Sets are a valuable data structure in Dart when you need to work with collections of unique elements and don't require elements to be in a specific order. They provide efficient methods for common set operations and membership testing.
void main() {
var numbers = {1, 2, 3, 3, 4, 4, 5}; // Duplicates are automatically removed
print(numbers); // Output: {1, 2, 3, 4, 5}
numbers.add(6);
print(numbers); // Output: {1, 2, 3, 4, 5, 6}
print(numbers.contains(3)); // Output: true
print(numbers.contains(7)); // Output: false
var set1 = {1, 2, 3};
var set2 = {3, 4, 5};
print(set1.union(set2)); // Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2)); // Output: {3}
print(set1.difference(set2)); // Output: {1, 2}
numbers.forEach((number) {
print(number * 2);
});
}
1. Empty Set
Use the Set constructor to create an empty set.
void main() {
Set<int> numbers = Set();
print(numbers); // Output: {}
}
⚠️ Using {} alone creates an empty Map, not a Set. To specify an empty set, use Set().
2. Set with Initial Values
Use a set literal with {} to initialize a set with elements.
void main() {
Set<String> fruits = {'Apple', 'Banana', 'Cherry'};
print(fruits); // Output: {Apple, Banana, Cherry}
}
3. Dynamic Set
If no type is specified, the set can hold elements of mixed types.
void main() {
Set<dynamic> mixedSet = {1, 'Hello', true};
print(mixedSet); // Output: {1, Hello, true}
}
4. Adding Elements to a Set
Use .add() or .addAll() to add elements to a set.
void main() {
Set<int> numbers = {1, 2, 3};
numbers.add(4); // Adds a single element
numbers.addAll([5, 6, 7]); // Adds multiple elements
print(numbers); // Output: {1, 2, 3, 4, 5, 6, 7}
}
5. Removing Elements from a Set
Use .remove() to remove a specific element.
void main() {
Set<String> colors = {'Red', 'Green', 'Blue'};
colors.remove('Green');
print(colors); // Output: {Red, Blue}
}
6. Using Set.from()
Create a set from another iterable, such as a list.
void main() {
List<int> numbers = [1, 2, 2, 3, 4];
Set<int> uniqueNumbers = Set.from(numbers);
print(uniqueNumbers); // Output: {1, 2, 3, 4}
}
7. Using Set.of()
Create a set from another collection using Set.of().
void main() {
List<String> names = ['Alice', 'Bob', 'Alice'];
Set<String> uniqueNames = Set.of(names);
print(uniqueNames); // Output: {Alice, Bob}
}
8. Unmodifiable Set
Create a read-only set using Set.unmodifiable().
void main() {
Set<int> numbers = Set.unmodifiable({1, 2, 3});
print(numbers); // Output: {1, 2, 3}
// numbers.add(4); // Error: Unsupported operation
}
9. Generate a Set Dynamically
Use Set.generate() to create a set programmatically.
void main() {
Set<int> squares = Set<int>.generate(5, (index) => index * index);
print(squares); // Output: {0, 1, 4, 9, 16}
}
10. Removing Duplicate Elements from a List
Convert a list to a set to remove duplicates.
void main() {
List<int> numbers = [1, 2, 2, 3, 4, 4, 5];
Set<int> uniqueNumbers = numbers.toSet();
print(uniqueNumbers); // Output: {1, 2, 3, 4, 5}
}
Unordered:
The elements in a set are not ordered.
Example:
void main() {
Set<String> items = {'Banana', 'Apple', 'Cherry'};
print(items); // Output: {Banana, Apple, Cherry} (order may vary)
}
Unique Elements:
Duplicate values are automatically ignored.
Example:
void main() {
Set<int> numbers = {1, 2, 2, 3};
print(numbers); // Output: {1, 2, 3}
}
Null Safety:
Sets cannot contain null unless explicitly allowed in the type declaration.
Set<int?> nullableSet = {1, 2, null};
print(nullableSet); // Output: {1, 2, null}
Common Methods:
.contains(value): Checks if a set contains a specific value.
.length: Returns the number of elements in the set.
.isEmpty / .isNotEmpty: Checks if the set is empty or not.
.intersection(Set): Returns common elements between two sets.
.union(Set): Combines elements from two sets.
.difference(Set): Returns elements that exist in one set but not the other.
void main() {
Set<int> setA = {1, 2, 3};
Set<int> setB = {3, 4, 5};
print('Union: ${setA.union(setB)}'); // {1, 2, 3, 4, 5}
print('Intersection: ${setA.intersection(setB)}'); // {3}
print('Difference: ${setA.difference(setB)}'); // {1, 2}
}
void main() {
Set<int> numbers = {1, 2, 3, 4, 5};
print(numbers);
}
void main() {
Set<String> fruits = {'Apple', 'Banana'};
fruits.add('Cherry');
print(fruits);
}
void main() {
Set<int> numbers = {10, 20, 30, 40};
numbers.remove(20);
print(numbers);
}
void main() {
Set<String> animals = {'Cat', 'Dog', 'Bird'};
print(animals.contains('Dog')); // true
print(animals.contains('Fish')); // false
}
void main() {
Set<String> colors = {'Red', 'Green', 'Blue'};
for (String color in colors) {
print(color);
}
}
void main() {
Set<int> setA = {1, 2, 3};
Set<int> setB = {3, 4, 5};
Set<int> unionSet = setA.union(setB);
print(unionSet); // {1, 2, 3, 4, 5}
}
void main() {
Set<int> setA = {1, 2, 3};
Set<int> setB = {3, 4, 5};
Set<int> intersectionSet = setA.intersection(setB);
print(intersectionSet); // {3}
}
void main() {
Set<int> setA = {1, 2, 3};
Set<int> setB = {3, 4, 5};
Set<int> differenceSet = setA.difference(setB);
print(differenceSet); // {1, 2}
}
void main() {
List<int> numbers = [1, 2, 2, 3, 4, 4, 5];
Set<int> uniqueNumbers = numbers.toSet();
print(uniqueNumbers); // {1, 2, 3, 4, 5}
}
void main() {
Set<int> setA = {1, 2};
Set<int> setB = {1, 2, 3, 4};
print(setA.isSubsetOf(setB)); // true
}
Here are 10 Dart programs demonstrating various operations using the Set collection. Sets are collections of unique elements in Dart, and they provide methods for adding, removing, and manipulating elements, among other useful operations.
void main() {
Set<String> fruits = {"Apple", "Banana", "Grapes"};
// Add elements
fruits.add("Orange");
fruits.addAll({"Mango", "Peach"});
// Remove an element
fruits.remove("Banana");
print("Fruits Set: $fruits");
}
void main() {
Set<int> numbers = {1, 2, 3, 4, 5};
if (numbers.contains(3)) {
print("The set contains the number 3.");
} else {
print("The number 3 is not in the set.");
}
}
void main() {
Set<int> setA = {1, 2, 3, 4};
Set<int> setB = {3, 4, 5, 6};
// Union of two sets
Set<int> unionSet = setA.union(setB);
print("Union of Set A and Set B: $unionSet");
}
void main() {
Set<int> setA = {1, 2, 3, 4};
Set<int> setB = {3, 4, 5, 6};
// Intersection of two sets
Set<int> intersectionSet = setA.intersection(setB);
print("Intersection of Set A and Set B: $intersectionSet");
}
void main() {
Set<int> setA = {1, 2, 3, 4};
Set<int> setB = {3, 4, 5, 6};
// Difference of two sets
Set<int> differenceSet = setA.difference(setB);
print("Difference of Set A and Set B: $differenceSet");
}
void main() {
List<int> numbers = [1, 2, 3, 4, 3, 2, 1];
// Convert list to set to remove duplicates
Set<int> uniqueNumbers = Set.from(numbers);
print("Unique Numbers: $uniqueNumbers");
}
void main() {
Set<String> colors = {"Red", "Green", "Blue"};
// Iterating over a set
for (var color in colors) {
print("Color: $color");
}
}
void main() {
Set<String> languages = {"Dart", "Python", "JavaScript"};
// Add multiple elements at once
languages.addAll({"Java", "C++"});
print("Languages Set: $languages");
}
void main() {
Set<String> cities = {"New York", "Los Angeles", "Chicago"};
// Clear all elements in the set
cities.clear();
print("Cities Set after clearing: $cities");
}
void main() {
Set<int> setA = {1, 2, 3};
Set<int> setB = {3, 2, 1};
Set<int> setC = {4, 5, 6};
// Check if two sets are equal
if (setA == setB) {
print("Set A is equal to Set B.");
} else {
print("Set A is not equal to Set B.");
}
if (setA == setC) {
print("Set A is equal to Set C.");
} else {
print("Set A is not equal to Set C.");
}
}
Adding and Removing: Adding new elements with add() and addAll(), and removing elements with remove().
Contains: Checking for the existence of an element using contains().
Union: Combining two sets using union().
Intersection: Finding common elements between two sets using intersection().
Difference: Finding the elements that are in one set but not in another using difference().
List to Set: Converting a list to a set to remove duplicate values using Set.from().
Iteration: Iterating through a set using a for loop.
addAll(): Adding multiple elements at once to the set.
Clear: Removing all elements from a set using clear().
Equality Check: Checking if two sets are equal using ==.
These programs highlight the versatility of sets in Dart, including operations like union, intersection, difference, and the ability to iterate over and manipulate sets efficiently.