Skip to main content

Flutter Dart HashSet with Example

In HashSet we will store the data single or multiple with collection in Hash Table. There are a condition that all the elements we will store in HashSet should have consistent equality including Hash Code. So in this tutorial we will learn about Flutter Dart HashSet with Example.

Flutter Dart HashSet with Example

1. Import 'dart:collection' class. Because this class has HashSet defined.
import 'dart:collection'; 
2. First we will learn about Creating a String type of HashSet. With same initialization we can make integer, double type of HashSet.
final testHashSet = HashSet<String>();
3. Adding single item in HashSet with add() method.
testHashSet.add('A');
4. Adding multiple items in HashSet with addAll() method.
testHashSet.addAll({'B', 'C', 'D'});
5. To get length of HashSet in dart we will use HashSet.length method.
print(testHashSet.length);
6. To check HashSet is empty or not we will use HashSet.isEmpty method.
print(testHashSet.isEmpty);
7. To find a specific value in HashSet we will use HashSet.contains(Value) method.
print(testHashSet.contains('B'));
8. To remove element from HashSet we will use HashSet.remove(Item).
testHashSet.remove('B');
9. To delete all the items from HashSet at once we will use HashSet.clear() method.
testHashSet.clear(); 
Source code for main.dart file:
import 'dart:collection'; 
void main() { 
  final testHashSet = HashSet<String>();
  testHashSet.add('A');
  print(testHashSet);
  testHashSet.addAll({'B', 'C', 'D'});
  print(testHashSet);
  print(testHashSet.length);
  print(testHashSet.isEmpty);
  print(testHashSet.contains('B'));
  testHashSet.remove('B');
  print(testHashSet);
  testHashSet.clear(); 
  print(testHashSet);
  
}
Output:
Flutter Dart HashSet with Example

Comments