Java 映射:如何获取与值关联的所有键?

Java 映射:如何获取与值关联的所有键?,java,collections,Java,Collections,给定一个映射,如何查找与特定值关联的所有键 例如: Map<Integer, Integer> map = new HashMap<Integer, Integer>(); map.put(1, 5); map.put(2, 2); map.put(3, 5); Collection<Integer> keys = map.values(5); // should return {1, 3} Map Map=newhashmap(); 地图.put(1,5)

给定一个映射,如何查找与特定值关联的所有键

例如:

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 5);
map.put(2, 2);
map.put(3, 5);
Collection<Integer> keys = map.values(5); // should return {1, 3}
Map Map=newhashmap();
地图.put(1,5);
地图.put(2,2);
地图.put(3,5);
集合键=映射值(5);//应该返回{1,3}

我正在寻找类似于Google Collections的东西,其中的值不是唯一的。

对于纯
java.util.Map
实现,恐怕您必须遍历映射条目并测试每个值:

for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
  if (entry.getValue().equals(desiredValue) {
    keys.add(entry.getKey());
  }
}
map.forEach((k,val) -> {
      if (val.equals(desiredValue) {
        keys.add(k);
      }
});