3

I'm new to hash table and I'm just figuring out the basic operations on it. I have a hash table created as shown below and inserted values also.

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

I am able to delete the element needed 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 following output

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

I am not able to find any method which helps with locating the element in the hashtable using the value as an index and deleting the element. How do I go about it?

5
  • 3
    Do you care about how efficient this operation is? If you do, you need a different data structure. Commented Feb 25, 2014 at 7:24
  • 2
    Uh, you are aware that a value can appear multiple times in a map, right? Commented Feb 25, 2014 at 7:28
  • @NPE How do I improve on it? Commented Feb 25, 2014 at 7:57
  • @fge Yes. I do get that. But like i said, I'm new to using hash tables. Just figuring out heads and tails of it now by using simple operations. Commented Feb 25, 2014 at 7:58
  • Well, the purpose of a Map is to access entries by key, not value. Some libraries (Guava for instance) do have bidirectional maps, but removing a key given a value is not a Map's "simple operation" ;) Commented Feb 25, 2014 at 8:00

3 Answers 3

7

try this

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

this will remove one entry with the specified value, if there may be multiple entries with the same value you can use this

ht.values().removeAll(Collections.singleton("ABCD"));
Sign up to request clarification or add additional context in comments.

Comments

4

Navigate using Map.entrySet() and check for Map.Entry#getValue() equality.
You can have a value multiple times so iterate entrySet using an Iterator and delete elements using 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();
    }
  }
}

Comments

1
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
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.