How to remove an item from a hash table using its value, and not the key?

I am new to the hash table and I will just figure out the basic operations on it. I have a hash table created as shown below and pasted values.

Hashtable<Integer , String> ht = new Hashtable<Integer , String>();
ht.put(1234, "ABCD");
ht.put(2345, "EFGH");
ht.put(4567, "IJKL");

I can delete the required item using the key, as shown below.

System.out.println("Deleting entry with key 2345");
ht.remove(2345);
System.out.println(ht.toString());

which gives the next exit

Deleting entry with key 2345
{4567=IJKL, 1234=ABCD}

I can not find any method to help find the item in the hash table, using the value as an index and deleting the item. How should I do it?

+3
source share
3 answers

try it

ht.values().remove("ABCD");

this will delete one record with the specified value, if there can be several records with the same value, you can use this

ht.values().removeAll(Collections.singleton("ABCD"));
+6
source

Map.entrySet() Map.Entry #getValue().
, entrySet Iterator Iterator.remove()

void deleteItem(String item) {
  Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
  while (it.hasNext()) {
    Map.Entry<Integer, String> entry = it.next();
    if(entry.getValue().equals(item)) {
      it.remove();
    }
  }
}
+4
Map<Integer, String> map = ...

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while (it.hasNext()) {
  Map.Entry<Integer, String> entry = it.next();

  // Remove entry if value equals xxx.
  if (entry.getValue() != null && entry.getValue().equals("X")) {
    // Do something
  }
}
+1
source

All Articles