How to use the HashTable.remove() method in Java
The HashTable.remove() method is present in the HashTable class inside the java.util package. The HashTable.remove() method is used to remove the key and its mapped value from the HashTable.
Parameter
Key: The key that is to be removed with its mapped value from theHashTable.
Return value
HashTable.keys() returns:
Value: The value that was mapped with the key to be removed.Null: If there was no mapping available with that key passed as an argument.
Code
Let’s have a look at the code below.
import java.util.*;class Main{public static void main(String[] args){Hashtable<Integer, String> h1 = new Hashtable<Integer, String>();h1.put(1, "Let's");h1.put(5, "see");h1.put(2, "Hashtable.remove()");h1.put(27, "method");h1.put(9, "in java.");System.out.println("The Hashtable is: " + h1);String removed_value = (String)h1.remove(2);System.out.println("Removed value is: " + removed_value);String rv = (String)h1.remove(24);System.out.println("Removed value is: " + rv);System.out.println("New table is: " + h1);}}
Explanation
-
In line 1, we import the required package.
-
In line 2, we make a
Mainclass. -
In line 4, we make a
mainfunction. -
In line 6, we declare a
Hashtableconsisting ofIntegertype keys andStringtype values. -
From lines 8 to 12, we insert values in the Hashtable by using the
Hashtable.put()method. -
In line 15, we display the original
Hashtable. -
In line 17, we use the
HashTable.remove()method to remove a specified key from theHashTableand display the value mapped with the removed key in line 18. -
In line 19, we use the
HashTable.remove()method to remove a new key from theHashTablewhose mapping is not defined in theHashTableand display the value mapped with the removed key in line 20. -
In line 22, we display the new
HashTable, which has the removed key-value pairs after the usage of theHashTable.remove()method.
In this way, we can use the HashTable.remove() method to remove the key and its mapped value from the HashTable.