Java Utility Library

Java Hashtable - remove() Method



The java.util.Hashtable.remove() method is used to remove the entry for the specified key only if it is currently mapped to the specified value.

Syntax

public boolean remove(Object key, Object value)

Parameters

key Specify key with which the specified value is associated.
value Specify value expected to be associated with the specified key.

Return Value

Returns true if the value was removed.

Exception

NA.

Example:

In the example below, the java.util.Hashtable.remove() method is used to remove the mapping for the specified key from the given hashtable.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating hashtable
    Hashtable<Integer, String> Htable = new Hashtable<Integer, String>();

    //populating hashtable
    Htable.put(101, "John");
    Htable.put(102, "Marry");
    Htable.put(103, "Kim");
    Htable.put(104, "Jo");

    //printing hashtable
    System.out.println("Before remove, Htable contains: " + Htable);    

    //remove mapping for 102 key
    Htable.remove(102, "Marry");
    //remove 103 key - with no effect as
    //the specified value is not matching 
    Htable.remove(103, "Sam");

    //printing hashtable
    System.out.println("After remove, Htable contains: " + Htable);  
  }
}

The output of the above code will be:

Before remove, Htable contains: {104=Jo, 103=Kim, 102=Marry, 101=John}
After remove, Htable contains: {104=Jo, 103=Kim, 101=John}

❮ Java.util - Hashtable