In this example we will show how to remove a key value pair from Hashtable object using remove method.
Source Code
package com.beginner.examples;
import java.util.Enumeration;
import java.util.Hashtable;
public class RemoveValueFromHashtable {
public static void main(String[] args) {
//create Hashtable.
Hashtable hashtable = new Hashtable();
hashtable.put("1", "Alice");
hashtable.put("2", "Bob");
hashtable.put("3", "Jack");
Enumeration enumeration1 = hashtable.elements();
System.out.println("Before remove, hashtable contains :");
while(enumeration1.hasMoreElements()) {
System.out.println(enumeration1.nextElement());
}
/*
* To remove a key value pair from Hashtable use Object remove(Object key) method of Hashtable.
*/
hashtable.remove("2");
Enumeration enumeration2 = hashtable.elements();
System.out.println("After remove, hashtable contains :");
while(enumeration2.hasMoreElements()) {
System.out.println(enumeration2.nextElement());
}
}
}
Output:
Before remove, hashtable contains :
Jack
Bob
Alice
After remove, hashtable contains :
Jack
Alice
References
Imported packages in Java documentation: