简体   繁体   中英

Retrieving Key from the Hash Map

I'm new to Java. I implemented a Hash Map as shown below. In a particular scenario I wanted to retrieve the key using values of the key. For Eg: If user enters "Dravid", then I need to retrieve "2" from the Hash Map.

And I want to use only one hash map to implement this.

Can anyone help me with this?

HashMap<String,String> streetno=new HashMap<String,String>();
    streetno.put("1", "Sachin");
    streetno.put("2", "Dravid");
    streetno.put("3","Sehwag");
    streetno.put("4", "Laxman");
    streetno.put("5", "Kohli");

Short version, so there is something to implement left for you:

Iterate over all entries of the map and compare your search string to the value of the entry. If it matches, return the key.

With a standard HashMap , the only thing you can do is iterate over the entries of the map until you find one that has the value that you are looking for and then return the key for that.

HashMap is made to quickly and efficiently lookup a value if you know the key, but not the other way around. There are some libraries that have maps that allow you to lookup the value by key as well as the other way around. Google Guava for example has a BiMap that supports this.

Using Guava's HashBiMap , you could do this:

BiMap<String, String> map = HashBiMap.create();
map.put("1", "Sachin");
map.put("2", "Dravid");
map.put("3", "Sehwag");
map.put("4", "Laxman");
map.put("5", "Kohli");

String key = map.inverse().get("Dravid");

To do this, you would need to use a bi-directional hashmap. Consider using the Apache Commons implementation .

Without it, you'd need to iterate over all the key / value pairs in the map and test for when the value equals "Dravid", then return the key. Like so:

for (Entry<String, String> pair : streetno.entrySet()) {
      if (pair.getValue().equals("Dravid")) {
        System.out.println("Found Dravid at key: " + pair.getKey());
      }
    }

You can do any of the above said answers, its also better to add this check before proceeding to the actual logic.

if(streetno.containsValue("Dravid")){
  // do logic
}
else
System.out.println("Not found");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM