Question:

How to access the key through the value in Hashtable in java language?

by  |  earlier

0 LIKES UnLike

Access the key

 Tags:

   Report

2 ANSWERS


  1. Loop through all of the items until you find the value you want, then you know the key. I'll give you a little example.

    Hashtable table = new Hashtable();

    table.Add("A", "1");

    table.Add("B", "2");

    table.Add("C", "3");

    // We want find the key corresponding to 2

    foreach (DictionaryEntry entry in table) {

        if (entry.Value = "2")

            // entry.Key is your key

    }


  2. Since you asked about Java and NOT Javascript, I'll give you a Java answer.

    1.  Use two Hashtables.  Potential problems if the mappings aren't 1-to-1, e.g. two keys have the same value associated.

    2.  Call entrySet() on the Hashtable to get the set of Map.Entry objects.  Each of these has a reference to the key and value objects.  Simply iterate these, checking the value (getValue()) against the one you have, and then using getKey() to get the associated key object.  Again, there are potential problems with other than 1-to-1 mappings.

    3.  Forget about Hashtable and use the Apache Jakarta Commons Collections extension library.  They have bi-directional map objects (BidiMap and its implementations) that will most likely serve your purposes better than the above two options.

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions