Hashmap反向键查找

时间:2013-11-29 04:58:32

标签: java

我有一个哈希映射,我引用该键来获取值:

// define the hashmap
private static final Map<String, String> map;
static {
   map.put("KEY1", "VALUE1");
   map.put("KEY2", "VALUE2");
}

// use the key to get a value 
private static final SomeObject MyObject1 = MyObject.compile(map.get("KEY1"));

...

但稍后在我的代码中我得到一个值,我需要获取密钥(我该怎么做这样的事情):

// some method that returns a value from the map based on conditional matching
String theValue = <SomeMethodThatReturns "VALUE1" or "VALUE2">();

// now I have theValue now **how can I get the key?**
System.out.println("Found Key Match: " + map.getKeyFromValue(theValue);  // ???

2 个答案:

答案 0 :(得分:4)

考虑使用Guava BiMap而不是HashMap:

  

bimap(或“双向地图”)是一种保留其值及其键值的唯一性的映射。此约束使bimaps支持“反向视图”,这是另一个包含与此bimap相同的条目但具有反向键和值的bimap。

然后,你可以这样做:

String key = map.inverse.get(theValue);

答案 1 :(得分:1)

如果使用Guava BiMap不是一个选项(see my other answer),那么你就会陷入迭代地图条目,直到找到具有匹配值的那个:

for (Map.Entry<String, String> entries : map.entrySet())
{
  if (entry.getValue().equals(theValue())
  {
    return entry.getKey();               // we found it
  }
}

// We couldn't find it ...