0

Let's suppose we want to associate to some set of distinct values a key, and suppose the mapping is injective. I want to be able to do things, and do them as quickly as possible: get the key of a given value and get the value corresponding to a give key. However, if possible I'd like to do key retrieval in O(1).

There are multiple ways to store key, value pairs in Java, for example with dictionaries or hashmaps. But neither is perfect: for example neither structure has a method for retrieving a key from a given value. My values are positive integer pairs. It might just be better to store the keys in a matrix so I can retrieve them immediately.

For my needs, what is the best option?

math_lover
  • 886
  • 7
  • 20

2 Answers2

2

If the keys are unique and the values are unique, that you can just create an inversed hashmap, but otherwise I would just loop trough the HashMap and when the value equals return the key.

Maxdola
  • 1,562
  • 2
  • 10
  • 29
  • The thing is, I really need to retrieve the key of a given value as quickly as possible. Wouldn't storing the keys in a matrix (indexed by the pairs (i,j) which are my values) be faster because key retrieval would be immediate? – math_lover Jan 04 '20 at 19:22
  • but this is also only possible if you have a key only one time and a value only one time and then depending on the object's complexity I would use the hashmaps instead of the arrays but for simpler objects, the matrix is also possible. – Maxdola Jan 04 '20 at 19:25
  • Yes all my keys and my values are distinct. I'm gonna be looking up keys for given values inside a for loop so this is why I really want to do key retrieval as fast as possible. – math_lover Jan 04 '20 at 19:30
  • ok then I would use the hashmap or the arrays given the complexity of the keys and values. – Maxdola Jan 04 '20 at 19:32
1

I would advocate using BidiMap by apache collections.

Idos
  • 15,053
  • 14
  • 60
  • 75