What is the HashSet.remove() method in Java?
The HashSet.remove() method is present in the HashSet class inside the java.util package. The HashSet.remove() method is used to remove only the specified element from the HashSet.
Example
Let’s understand with the help of an example.
Suppose that the Hashset contains the following: [1, 8, 5, 3, 0]. We execute the below statements on this hashset:
Hashset1.remove(8);Hashset1.remove(0);
After using the remove() method, the HashSet contains [1, 5, 3].
Syntax
public boolean remove(Object obj)
Parameters
The HashSet.remove() accepts one parameter:
obj: TheObjectofHashSettype that needs to be removed from theHashSet.
Return value
The HashSet.remove() method returns true if the HashSet gets changed as a result of the call to the method.
Code
Let’s have a look at the code now.
import java.io.*;import java.util.HashSet;class Main{public static void main(String args[]){HashSet<Integer> hash_set1 = new HashSet<Integer>();hash_set1.add(1);hash_set1.add(8);hash_set1.add(5);hash_set1.add(3);hash_set1.add(0);System.out.println("hash_set1 before calling remove(): "+ hash_set1);boolean removeVal1;boolean removeVal2;removeVal1 = hash_set1.remove(150);removeVal2 = hash_set1.remove(8);System.out.println("hash_set1 after calling remove(): "+ hash_set1);System.out.println("the removal of 8 was: " + removeVal2);System.out.println("the removal of 150 was: " + removeVal1);}}
Explanation
- In line 8, we declare a
HashSetof integer type, i.e.,hash_set1. - From lines 9 to 13, we add the elements into the
HashSetby using theHashSet.add()method. - In line 15, we display the
HashSetbefore calling theremove()method. - In lines 19 and 20, we call the
remove()function to remove specific elements from theHashSetand assign the returned values to boolean variables. - When
150is passed as the argument, nothing happens, as it is not present. But when8is removed, the change is reflected. - In line 21, we display the
HashSetafter calling theremove()method. - In lines 23 and 24, the returned values of the
remove()method are displayed.