0

I want to retrieve the specific key associated with the value in a hashmap

I want to retrieve the key of "ME", how can I get it?

Code snippet :

HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"I");
map.put(2,"ME");
Rajhrita
  • 105
  • 1
  • 3
  • 11

5 Answers5

3

There's a small problem with what you are trying to do. There can be multiple occurrences of the same value in a hashmap, so if you look up the key by value, there might be multiple results (multiple keys with the same value).

Nevertheless, if you are sure this won't occur, it can be done; see the following example:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        HashMap<Integer, String> map = new HashMap<Integer, String>();
        map.put(5, "vijf");
        map.put(36, "zesendertig");
    }
    static Integer getKey(HashMap<Integer, String> map, String value) {
        Integer key = null;
        for(Map.Entry<Integer, String> entry : map.entrySet()) {
            if((value == null && entry.getValue() == null) || (value != null && value.equals(entry.getValue()))) {
                key = entry.getKey();
                break;
            }
        }
        return key;
    }
}
Tom
  • 4,096
  • 2
  • 24
  • 38
2

Iterate over the entries of the map :

for(Entry<Integer, String> entry : map.entrySet()){
  if("ME".equals(entry.getValue())){
    Integer key = entry.getKey();
    // do something with the key
  }
}
kgautron
  • 7,915
  • 9
  • 39
  • 60
0

You will have to iterate through the collection of keys to find your value.

Take a look at this post for details: Java Hashmap: How to get key from value?

Community
  • 1
  • 1
bharris9
  • 335
  • 3
  • 14
0

If your values are guaranteed to be unique use Guava BiMap (the HashMap counterpart is called HashBiMap.

    Integer key = map.inverse().get("ME");

Guava Documentation.

Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118
  • This post talk about "HashMap" not BiMap .... "I think" (How to get key depending upon the value from hashmap) –  Nov 16 '15 at 13:19
0
/**
 * Return keys associated with the specified value
 */
public List<Integer> getKey(String value, Map<Integer, String> map) {
  List<Integer> keys = new ArrayList<Integer>();
  for(Entry<Integer, String> entry:map.entrySet()) {
    if(value.equals(entry.getValue())) {
      keys.add(entry.getKey());
    }
  }
  return keys;
}
baraber
  • 3,296
  • 27
  • 46