查找值的键,这是其他hashmap中的键

时间:2016-02-23 22:11:28

标签: java

考虑我有一个哈希映射图(两个,两个) 和其他哈希映射双关语(twooo,3)

现在我需要获得密钥"两个"来自价值" 3"

我该怎么做?

2 个答案:

答案 0 :(得分:0)

假设您为每个键设置了不同的值,您可以执行以下操作:

private Map<String, Integer> team1 = new HashMap<String, Integer>();

  team1.put("1", 1);
  team1.put("2", 2)


private String getKey(Integer value){
   for(String key : team1.keySet()){
     if(team1.get(key).equals(value)){
        return key; //return the first found
     }
  }
  return null;
}

以相同的方式遍历其他哈希映射以查找其他hashMap中的键值的键。

答案 1 :(得分:0)

如果你正在使用HashMap,这将是非常低效的,你必须遍历两个地图中的值以找到你正在寻找的关键字,如:

public static <K1, VK, V2> K1 findKeyInFirstMap(
    Map<K1, VK> map1, Map<VK, V2> map2, V2 value) {
  VK valueKey = null;
  for (Entry<VK, V2> e : map2.entrySet()) {
    if (e.getValue().equals(value)) {
      valueKey = e.getKey();
      break;
    }
  }
  if (valueKey == null) {
    throw new IllegalArgumentException(value + " not found in map2");
  }
  for (Entry<K1, VK> e : map1.entrySet()) {
    if (e.getValue().equals(valueKey)) {
      return e.getKey();
    }
  }
  throw new IllegalArgumentException(valueKey + " not found in map1");
}

这假设您的地图没有null个键或值,但为什么要对自己这样做呢? :)

使用双向映射(如Guava's BiMap)会更有效率。使用BiMap,它更简单,而O(1)代替O(n):

map1.inverse().get(map2.inverse().get(value));

或者,使用与前一种方法相同的错误语义:

public static <K1, VK, V2> K1 findKeyInFirstMap(
        BiMap<K1, VK> map1, BiMap<VK, V2> map2, V2 value) {
  VK valueKey = map2.inverse().get(value);
  if (valueKey == null) {
    throw new IllegalArgumentException(value + " not found in map2");
  }
  K1 key = map1.inverse().get(valueKey);
  if (key == null) {
    throw new IllegalArgumentException(valueKey + " not found in map1");
  }
  return key;
}