Various Operations on HashSet in Java
A HashSet is a collection in Java that contains only distinct elements. The order of the elements is not maintained, and duplicate values cannot be stored. Basic operations like add, delete, contain, and size can be performed using HashSet in constant time. We will go through several Java operations on HashSet in this tutorial.
Adding Elements to HashSet:
We employ the add() method to include a new element in a hash set. If an element is successfully added, the add() method returns true; otherwise, it returns false if the element is already existing in the HashSet. The following is the syntax for adding an element to a hash set:
Removing Elements from HashSet:
The remove() method is used to take an element out of a hash set. The HashSet's given element is eliminated via the remove() method. The following syntax is used to remove an element from a hash set:
Checking if an Element is Present in HashSet:
The contains() method is used to determine whether an element is present in a HashSet. If the requested element is present in the HashSet, the contains() method returns true; otherwise, it returns false. The following syntax can be used to determine whether an element is present in a hash set:
With the use of the clear() method, we can eliminate every element from a HashSet. All of the elements in the HashSet are removed using the clear() method. The following is the syntax for clearing a HashSet:
Checking if HashSet is Empty:
The isEmpty() method is used to determine whether a HashSet is empty. If the HashSet is empty, the isEmpty() method returns true; otherwise, it returns false. The following syntax can be used to determine whether a HashSet is empty:
Iterating Over HashSet:
We can use a for-each loop or an iterator to loop through a HashSet. The following syntax describes how to use an iterator to loop through a HashSet:
The following is the syntax for a for-each loop when iterating over a HashSet:
Is 'element1' present in the HashSet? true Is the HashSet empty? true Element: element4 Element: element5 Element: element4 Element: element5
In conclusion, the Java collection known as HashSet is beneficial for storing distinct components. We can use different methods to iterate through HashSet, add and delete elements from HashSet, verify if an element is present, clear HashSet, and check if HashSet is empty. We can use HashSet in our Java programmes more successfully if we comprehend these actions.