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.

HashSet is an unordered, hashtable-based set. Read more about HashSet here.

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 HashSet
HashSet set = new HashSet();
// add 2 elements to the set
set.add(10);
set.add(20);
print("set is : $set");
// get the size of the HashSet
print("The size is : ${set.length}");
// add 2 more elements to the set
set.add(30);
set.add(40);
print("\nset is : $set");
// get the size of the HashSet
print("The size is : ${set.length}");
}

Explanation

In the code above:

  • Line 1: We import the collection library.
  • Line 4: We create a HashSet named set.
  • Lines 6 to 7: We use the add() method to add two elements, 10 and 20, to the set.
  • Line 11: We use the length property to get the number of elements present in set. In our case, set has two elements, so length returns 2.
  • Lines 14 to 15: We use the add() method to add two more elements, 30 and 40, to the set.
  • Line 18: We use the length property to get the number of elements present in set. set has four elements, so length returns 4.

Free Resources