如何在java中创建2路地图 [英] How to create a 2 way map in java
问题描述
我需要一个数据结构来以 1:1 的关系存储 string-int 值对,并且也能够从对应的任何一种方式进行查找.
我编写了一个带有 Hashtable 和 String 数组的类并存储了 2 次数据并使用内置函数进行查找.
我的问题是有没有更好的方法来实现这一点?更好的是我的意思是高效并且不存储数据 2 次,最好也不要编写大量代码 :P.
看来您可能正在寻找 bimap.
Google 集合(现在是 Guava 的一部分)包含一个 BiMap
接口与一些实现.>
来自 BiMap
文档:
双映射(或双向映射")是一个保留唯一性的地图它的价值观以及它的价值观键.此约束启用双映射支持逆向观点",即另一个包含相同的双图条目作为这个 bimap 但有反转键和值.
BiMap.inverse
方法似乎返回一个Map
,以值为键,以键为值,这样Map
可用于对值调用 get
并检索键.
另外inverse
返回的Map
是底层数据的视图,所以不需要对原始数据做额外的拷贝.
来自 BiMap.inverse
方法文档:
返回这个的逆视图bimap,它映射了这个 bimap 的每一个值到其关联的键.他们俩双图由相同的数据支持;对一个的任何更改都会出现在其他.
I need a data structure to store string-int value pairs in an 1:1 relationship, and being able too look up from either way their counterpart.
I wrote a class with a Hashtable and a String array and stored the data 2 times and used the built in functions for lookup.
My question is that is there a nicer way to accomplish this? And by nicer I mean being efficient and not storing the data 2 times, and preferably without writing a ton of code either :P.
It seems like you may be looking for a bimap.
The Google Collections (now a part of Guava) contains an BiMap
interface with a few implementations.
From the BiMap
documentation:
A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.
The BiMap.inverse
method appears to return a Map
with the values as the keys, and the keys as the values, so that Map
can be used to call get
on the value and retrieve a key.
In addition the Map
returned by inverse
is a view of the underlying data, so it does not have to make extra copies of the original data.
From the BiMap.inverse
method documentation:
Returns the inverse view of this bimap, which maps each of this bimap's values to its associated key. The two bimaps are backed by the same data; any changes to one will appear in the other.
这篇关于如何在java中创建2路地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!