Java key - key map

我怕爱的太早我们不能终老 提交于 2020-01-13 10:06:17

问题


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";

回答1:


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




回答2:


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"



回答3:


Yes, there is BiMap from Google Collections.




回答4:


Or for reversible enums see this Stackoverflow question.



来源:https://stackoverflow.com/questions/1680463/java-key-key-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!