我需要将名称和 ID 存储为键值对。但是,我有时需要在我的程序中同时按名称和 ID 进行查找。我不想创建两个 HashMap(或者通过存储 name-id 和 id-name 对来增加内存消耗)
什么是适合它的数据结构?java中是否有为此的标准实现?
我需要将名称和 ID 存储为键值对。但是,我有时需要在我的程序中同时按名称和 ID 进行查找。我不想创建两个 HashMap(或者通过存储 name-id 和 id-name 对来增加内存消耗)
什么是适合它的数据结构?java中是否有为此的标准实现?
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.
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.)
Commons-Collections 有您可以使用的 BidiMap:
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/BidiMap.html