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:
HashSetis an unordered,Hashtable-based set. You can read more aboutHashSethere.
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 HashSetHashSet set = new HashSet();print("set is : $set");// check it the set is not emptyprint("Is set Not Empty : ${set.isNotEmpty}");// add elements to the setset.add(10);set.add(20);print("set is : $set");// check it the set is not emptyprint("Is set Not Empty : ${set.isNotEmpty}");}
Code explanation
-
Line 1: We import the collection library.
-
Line 4: We create a
HashSetwith the nameset. -
Line 8: We use the
isNotEmptyproperty to check ifsetis empty or not. In this case,setdoes not contain any elements, so the property returnsFalse. -
Lines 11–12: We use the
add()method to add two elements,10and20, to the set. -
Line 15: We use the
isNotEmptyproperty to check ifsetis empty or not. Now,setcontains two elements, so the property returnsTrue.