1

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");
Kiran Bhat
  • 3,717
  • 4
  • 20
  • 18
  • 2
    You probably want to see this [link](http://stackoverflow.com/questions/1383797/java-hashmap-how-to-get-key-from-value) first. Perhaps it will help resolve your problem. – Frankline Jan 24 '12 at 10:56
  • 1
    That's not a usual using of a Map, so you should probably rethink your approach: maybe you need to swap your keys and values, so keys will be values, and values will be keys. – Egor Jan 24 '12 at 10:58

4 Answers4

3

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.

Urs Reupke
  • 6,791
  • 3
  • 35
  • 49
  • Yes.. Can you tell me which function I need to use to iterate over all entries of the map and to compare the string?? – Kiran Bhat Jan 24 '12 at 10:57
2

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");
Jesper
  • 202,709
  • 46
  • 318
  • 350
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());
      }
    }
Cuga
  • 17,668
  • 31
  • 111
  • 166
1

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");
Jayy
  • 2,368
  • 4
  • 24
  • 35