开发者

Map: How to get all keys associated with a value?

Given a Map, how do I look up all keys associated with开发者_StackOverflow社区 a particular value?

For example:

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}

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


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.

From Java 8 onwards you can use map.forEach:

map.forEach((k,val) -> {
      if (val.equals(desiredValue) {
        keys.add(k);
      }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜