How to check if a HashSet is not empty in Dart

Overview

We can use the isNotEmpty property of HashSet to confirm that a HashSet is not empty.

Note: HashSet is an unordered, Hashtable-based set. You can read more about HashSethere.

Syntax

bool isNotEmpty

Return value

This property returns True if the set contains at least one element. Otherwise, it returns False.

Code

The code below demonstrates how to check if a HashSet is not empty.

import 'dart:collection';
void main() {
// create a new HashSet
HashSet set = new HashSet();
print("set is : $set");
// check it the set is not empty
print("Is set Not Empty : ${set.isNotEmpty}");
// add elements to the set
set.add(10);
set.add(20);
print("set is : $set");
// check it the set is not empty
print("Is set Not Empty : ${set.isNotEmpty}");
}

Code explanation

  • Line 1: We import the collection library.

  • Line 4: We create a HashSet with the name set.

  • Line 8: We use the isNotEmpty property to check if set is empty or not. In this case, set does not contain any elements, so the property returns False.

  • Lines 11–12: We use the add() method to add two elements, 10 and 20, to the set.

  • Line 15: We use the isNotEmpty property to check if set is empty or not. Now, set contains two elements, so the property returns True.

Free Resources