1

If I have a HashMap<KEY, VALUE> and I need fast look up of the key by the value is there any other approach besides creating a second HashMap<VALUE, KEY> that store the same data but using the value as the key?
Is there any approach/tick about this? If it makes a difference my interest is about String both as key and value
Note: I am on Java 7

Update:
I am not sure why the other question is a duplicate as I am asking a specific way on implementing this.
Unless the only/best way is a 2 way map I can't see why this is a duplicate

Jim
  • 18,826
  • 34
  • 135
  • 254
  • How *fast* ? But most certainly having two maps is the answer – Dici Oct 07 '15 at 19:55
  • 4
    Possible duplicate of [How to create a 2 way map in java](http://stackoverflow.com/questions/3430170/how-to-create-a-2-way-map-in-java) – Dici Oct 07 '15 at 19:56
  • @Dici: It should not be O(N). I was interested if there is an efficient way to avoid the duplicate copy of data – Jim Oct 07 '15 at 19:56
  • @Dici:The answers in the post you linked are about 2 maps. That part I already knew to implement – Jim Oct 07 '15 at 19:57
  • 2
    Keep in mind that you're not creating a duplicate copy of the data. You'd be creating duplicate references to the same data. – Yosef Weiner Oct 07 '15 at 19:58
  • @voters: Please see my update and elaborate a bit – Jim Oct 07 '15 at 20:05
  • 1
    As a general rule of thumb, Guava makes things better than you do. I would trust them on that – Dici Oct 07 '15 at 20:12
  • "Unless the only/best way is a 2 way map I can't see why this is a duplicate" well, it is essentially the only way, so yes. (And Guava's implementation is noticeably smarter than just having two maps.) – Louis Wasserman Oct 07 '15 at 20:18

1 Answers1

1

Short answer: no, there isn't.

You need two maps. If you want to use O(1) time for both, that means two hashmaps.

If you're worried about space, don't worry so much: you're just storing duplicate pointers, and not two strings.

I.e., you're just storing

HashMap<String* k, String* v> normal;
HashMap<String* k, String* v> inverse;

rather than entire strings. (Although pointers kind of don't exist in Java.)

Joseph Nields
  • 5,527
  • 2
  • 32
  • 48