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: The Object of HashSet type that needs to be removed from the HashSet.

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 HashSet of integer type, i.e., hash_set1.
  • From lines 9 to 13, we add the elements into the HashSet by using the HashSet.add() method.
  • In line 15, we display the HashSet before calling the remove() method.
  • In lines 19 and 20, we call the remove() function to remove specific elements from the HashSet and assign the returned values to boolean variables.
  • When 150 is passed as the argument, nothing happens, as it is not present. But when 8 is removed, the change is reflected.
  • In line 21, we display the HashSet after calling the remove() method.
  • In lines 23 and 24, the returned values of the remove() method are displayed.

Free Resources