In this tutorial we are gonna see how to remove a key-value mapping from Hashtable. We will be using remove(Object key) method of Hashtable class.
Example
Method used in the below program is:
public V remove(Object key)
: Removes the key (and its corresponding value) from this hashtable. This method does nothing if the key is not in the hashtable.
import java.util.Hashtable; public class RemoveMappingExample { public static void main(String[] args) { // Creating a Hashtable Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>(); // Adding Key and Value pairs to Hashtable hashtable.put(11,"AA"); hashtable.put(22,"BB"); hashtable.put(33,"CC"); hashtable.put(44,"DD"); hashtable.put(55,"EE"); //Before remove System.out.println("Hashtable contains:" + hashtable); // Removing key-value pairs for key 44 Object removedValue = hashtable.remove(44); //After remove System.out.println("After remove:"); System.out.println("Hashtable Key-value pairs: " + hashtable); } }
Output:
Hashtable contains:{55=EE, 44=DD, 33=CC, 22=BB, 11=AA} After remove: Hashtable Key-value pairs: {55=EE, 33=CC, 22=BB, 11=AA}
In the above program we have provided the key 44 while calling remove(key) method so the key-value mapping corresponding to key 44 has been removed from Hashtable and the method returned the value mapped to the key 44.
Leave a Reply