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