• Post Reply Bookmark Topic Watch Topic
  • New Topic

reverse lookup in hashmap  RSS feed

 
matt alberty
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a hashmap and need to do a loookup on the values in it both ways. Anyone have any suggestions on how to handle this?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Matt,

Welcome to JavaRanch!

There are several different possible approaches. If you don't need to do this much, and the map isn't too big, you can simply iterate over the Map.Entry objects using Map.entrySet().iterator(). Each Map.Entry is a key/value pair, so just look at each value, and when you find the target, return the key.

Another thing you can do that it much faster is to keep two maps, a forward and reverse one. Then you can just look up things in whichever map is required.

Neither of these schemes works quite right if the values in the map aren't unique -- i.e., two different keys, same value. Then you'd have to clarify the problem.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you can check if a Map contains a specific value or key using the two contains() methods defined in the JavaDocs. You can only get a value by key though. It depends if you need to do more with the value than see if it is in the Map.
[ May 27, 2005: Message edited by: Paul Sturrock ]
 
matt alberty
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys .. I'll try what you suggested .. what I need to do is look in a map that contains a key/value pair such as (101,ACTIVE). I'll have the 101 value as input so I can translate it to ACTIVE. On the outbound though I have the ACTIVE key now and need the 101 value. We explored creating 2 maps but were are worried about having too store 2 maps.
 
Horatio Westock
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are interested, there is a bi-directional map interface (and implementations) in the Jakarta Commons package, called BidiMap. There are also associated OrderedBidiMap, SortedBidiMap etc.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!