I want to get the key of a HashMap using the value.
hashmap = new HashMap<String, Object>(); haspmap.put("one", 100); haspmap.put("two", 200);
Which means i want a function that will take the value 100 and will return the string one.
It seems that there are a lot of questions here asking the same thing but they don't work for me.
Maybe because i am new with java.
How to do it?
If your hashmap contain unique key to unique value mapping, you can maintain one more hashmap that contain mapping from Value to Key. In that case you can use second hashmap to get key.
Explanation: The key is hashed twice; first by hashCode() of Object class and then by internal hashing method of HashMap class.
Keys are unique once added to the HashMap , but you can know if the next one you are going to add is already present by querying the hash map with containsKey(..) or get(..) method.
The put method in HashMap is defined like this:
Object put(Object key, Object value)
key is the first parameter, so in your put, "one" is the key. You can't easily look up by value in a HashMap, if you really want to do that, it would be a linear search done by calling entrySet()
, like this:
for (Map.Entry<Object, Object> e : hashmap.entrySet()) { Object key = e.getKey(); Object value = e.getValue(); }
However, that's O(n) and kind of defeats the purpose of using a HashMap unless you only need to do it rarely. If you really want to be able to look up by key or value frequently, core Java doesn't have anything for you, but something like BiMap from the Google Collections is what you want.
We can get KEY
from VALUE
. Below is a sample code_
public class Main { public static void main(String[] args) { Map map = new HashMap(); map.put("key_1","one"); map.put("key_2","two"); map.put("key_3","three"); map.put("key_4","four");
System.out.println(getKeyFromValue(map,"four")); } public static Object getKeyFromValue(Map hm, Object value) { for (Object o : hm.keySet()) { if (hm.get(o).equals(value)) { return o; } } return null; } }
I hope this will help everyone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With