How to get the size of a HashSet in Dart
To get the size of a HashSet (number of elements present) in Dart, we use the length property of the HashSet.
HashSetis an unordered, hashtable-based set. Read more aboutHashSethere.
Syntax
int length
Return value
This property returns an int value that denotes the number of elements present in the HashSet.
Code
The code below demonstrates how to get the size of a HashSet in Dart.
import 'dart:collection';void main() {// create a new HashSetHashSet set = new HashSet();// add 2 elements to the setset.add(10);set.add(20);print("set is : $set");// get the size of the HashSetprint("The size is : ${set.length}");// add 2 more elements to the setset.add(30);set.add(40);print("\nset is : $set");// get the size of the HashSetprint("The size is : ${set.length}");}
Explanation
In the code above:
- Line 1: We import the collection library.
- Line 4: We create a
HashSetnamedset. - Lines 6 to 7: We use the
add()method to add two elements,10and20, to the set. - Line 11: We use the
lengthproperty to get the number of elements present inset. In our case,sethas two elements, solengthreturns2. - Lines 14 to 15: We use the
add()method to add two more elements,30and40, to the set. - Line 18: We use the
lengthproperty to get the number of elements present inset.sethas four elements, solengthreturns4.