Set Interface
Sets are one of the essential part of Dart Collections. A set is defined as an unordered collection of unique objects.
Syntax:
Set fruits = Set.from("Mango", "Apple", "Banana")
Example:
As discussed earlier a set stores a group of objects that are not repeating. A sample program is shown below.
void main() {
// Initializing the Set and Adding the values
Set geekSet = new Set();
geekSet.addAll([9,1,2,3,4,5,6,1,1,9]);
// Looping over the set
for(var el in geekSet){
print(el);
}
// length of the set.
print('Length: ${geekSet.length}');
// printing the first element in the set
print('First Element: ${geekSet.first}');
// Deleting an element not present. No Change
geekSet.remove(10);
// Deleting an element 9
geekSet.remove(9);
print(geekSet);
}
Output:
9
1
2
3
4
5
6
Length: 7
First Element: 9
{1, 2, 3, 4, 5, 6}
Classes Associated with Set Interfaces
Classes | Description |
---|---|
Set<E> | Collection of objects in which each of the objects occurs only once |
HashSet<E> | Set based on hash table i.e unordered set. |
LinkedHashSet<E> | Similar to HashSet but based on LinkedList. |
SplayTreeSet<E> | Set based on Self Adjusting Binary Search Tree organizing elements to allow fast access. |
UnmodifiableSetView<E> | Set that prevents any modifications. |
Hashset:
In the Dart programming language, a HashSet is a collection that stores a set of unique elements, where each element can be of any type. Here is an example of how to use a HashSet in Dart:
import 'dart:collection';
void main() {
// Create a new HashSet
var set = HashSet<String>();
// Add some elements to the set
set.add('apple');
set.add('banana');
set.add('cherry');
// Check if an element is in the set
print(set.contains('apple')); // Output: true
print(set.contains('pear')); // Output: false
// Iterate over the set
set.forEach((element) {
print(element);
});
}
Output:
apple
banana
cherry
Dart – Collections
Collections are groups of objects that represent a particular element. The dart::collection library is used to implement the Collection in Dart. There are a variety of collections available in Dart.
Contact Us