2

可能重复:
Map<K1, K2, V> 的任何实现,即两个键?

我需要将名称和 ID 存储为键值对。但是,我有时需要在我的程序中同时按名称和 ID 进行查找。我不想创建两个 HashMap(或者通过存储 name-id 和 id-name 对来增加内存消耗)

什么是适合它的数据结构?java中是否有为此的标准实现?

4

3 回答 3

3

You can use also guava's BiMap. And to get the inverse map is as simple as:

BiMap<Integer, String> biMap = HashBiMap.create();
biMap.put(1, "a");
biMap.put(2, "b");
BiMap<String, Integer> invertedMap = biMap.inverse(); //to get the name,id map

The only constraint is that your keys and values should be unique.

于 2012-11-02T20:43:31.740 回答
0

Guava has HashBiMap which keeps track of both directions of a mapping for you. Currently, its implementation basically just maintains a HashMap in each direction, but the next release will use a custom data structure saving something like ~38% on memory.

Essentially, HashBiMap behaves exactly like a Map, except that it rejects duplicate values, and you can get a view of the other direction -- values to keys -- by calling inverse().

(Disclosure: I contribute to Guava.)

于 2012-11-02T20:43:11.647 回答
0

Commons-Collections 有您可以使用的 BidiMap:

http://commons.apache.org/collections/apidocs/org/apache/commons/collections/BidiMap.html

于 2012-11-02T20:24:45.053 回答