Is there a data structure with 2 indizes / a key-key data-structure?

ndsvw :

Is there a data structure in Java (java util, guava...) that allows me to store "key value" pairs that can also be interpreted as value-key?

Example:

Datastructure d = new Datastructure();

d.add(1, "foo");
d.add(21 "bar");
d.add(33 "hello");
d.add(55 "world");

A function like d.get1(1) should return foo. A function like d.get2("foo") should return 1.

A function like d.get1(33) should return hello. A function like d.get2("hello") should return 33.

...

Is there something that works like this?

Razib :

What you are looking for is essentially implemented by Guava's BiMap.
You can use guava's BiMap like this -

BiMap<Integer, String> biMap = HashBiMap.create();
biMap.put(1, "foo");
biMap.put(21, "bar");

System.out.println(biMap.get("1"))); //foo
System.out.println(biMap.inverse().get("bar"))); //21

Link:
- Guide to guava BiMap
- BiMap java doc

Alternatively, you can use apache common BiDiMap like this:

BidiMap<String, String> map = new DualHashBidiMap<>();
map.put(1, "foo");
map.put(21, "bar");
System.out.println(map.get(1)); //1

//reversing the mapping 
BidiMap<String, String> reversedMap = map.inverseBidiMap();
System.out.println(reversedMap.get("foo")); //1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116044&siteId=1