Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key from a HashMap using the value [duplicate]

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?

like image 335
kechap Avatar asked Nov 13 '11 16:11

kechap


People also ask

Can I get HashMap key from value?

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.

Which of the method is used in case of HashMap to identify duplicate keys?

Explanation: The key is hashed twice; first by hashCode() of Object class and then by internal hashing method of HashMap class.

How do I find duplicate keys on a map?

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.


2 Answers

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.

like image 78
kbyrd Avatar answered Sep 23 '22 01:09

kbyrd


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.

like image 44
Rupesh Yadav Avatar answered Sep 21 '22 01:09

Rupesh Yadav