Reputation: 3847
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");
Upvotes: 1
Views: 347
Reputation: 2436
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");
Upvotes: 1
Reputation: 17904
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());
}
}
Upvotes: 1
Reputation: 206776
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");
Upvotes: 2
Reputation: 6921
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.
Upvotes: 3