开发者

Java key - key map

开发者 https://www.devze.com 2022-12-11 03:05 出处:网络
I need开发者_高级运维 a kind of map which is accessible in two directions, so with a key-key structure instead of key-value. Does this exist in Java? If not, what is the best way to create it?

I need开发者_高级运维 a kind of map which is accessible in two directions, so with a key-key structure instead of key-value. Does this exist in Java? If not, what is the best way to create it?

So example:

mySpecialHashMap.put("key1", "key2");

mySpecialMap.getL2R("key1") returns "key2";
mySpecialMap.getR2L("key2") returns "key1";


So you want a bidirectional map. You can use Apache Commons Collections BidiMap or Google Collections BiMap for this.


You might want to look at BiMap from the Guava library (formerly known as Google Collections).

An example where a HashBiMap is used as the "mySpecialHashMap":

BiMap<String, String> myBiMap = HashBiMap.create();
myBiMap.put("key1", "key2");

myBiMap.get("key1"); // returns "key2"
myBiMap.inverse().get("key2"); // returns "key1"


Yes, there is BiMap from Google Collections.


Or for reversible enums see this Stackoverflow question.

0

精彩评论

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

关注公众号