地图:如何获得与值相关联的所有键? [英] Map: How to get all keys associated with a value?

查看:115
本文介绍了地图:如何获得与值相关联的所有键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定地图,如何查找与特定值关联的所有键?

Given a Map, how do I look up all keys associated with a particular value?

例如:

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}

我正在寻找类似于Google Collections' a href =http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/BiMap.html =nofollow> BiMap 其中值不唯一。

I'm looking for something similar to Google Collections' BiMap where values are not unique.

推荐答案

使用简单的 java.util.Map 害怕您必须迭代地图条目并测试每个值:

With plain java.util.Map implementations, I am afraid you must iterate through the map entries and test each value:

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

如果你想要更好的性能,你可能需要建立一个从值到键列表的并行映射不知道任何现有的集合做这个,但它不应该难以实现。

If you want better performance, you may want to build up a parallel mapping from values to lists of keys. I don't know of any existing collection doing this, but it should not be difficult to implement.

这篇关于地图:如何获得与值相关联的所有键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆