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.
We can also use Apache Commons Collection, which provides an efficient map implementation MultiKeyMap that maps multiple keys to a value. MultiKeyMap provides get, containsKey, put, and remove for individual keys.
You can't have an hash map with multiple keys, but you can have an object that takes multiple parameters as the key. Create an object called Index that takes an x and y value. Then have your HashMap<Index, Value> to get your result. :) You need to override hashCode and equals .
Add Items to make a Map To make a map, place 8 papers and 1 compass on Java Edition (PC/Mac), Xbox and PS in the 3x3 crafting grid. In PE and Windows 10, you need 9 papers to make a map.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With