Retrieving Key from the Hash Map

人盡茶涼 提交于 2019-12-24 07:13:10

问题


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");

回答1:


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());
      }
    }



回答2:


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.




回答3:


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");



回答4:


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");


来源:https://stackoverflow.com/questions/8985573/retrieving-key-from-the-hash-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!