10

I want a data structure that maps from key to object and vice-versa(unlike HashMaps that map only in a single direction.) An idea could be to store the HashMap within itself for reverse look-up, but it will be an inefficient approach.

What would be the best implementation for two-way mapping?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
dev
  • 2,474
  • 7
  • 29
  • 47

1 Answers1

10

Simplest idea: wrapper class which contains 2 maps, second with swapped keys/values. You will keep O(1) complexity and will use only slightly more memory since you will (probably) keep there reference to object.

IProblemFactory
  • 9,551
  • 8
  • 50
  • 66
  • I mentioned this idea in question itself, but I guess there might be better implementations in terms of efficiency. – dev Feb 20 '14 at 16:38
  • 3
    Why do you think it will be inefficient? You will keep `O(1)` complexity. – IProblemFactory Feb 20 '14 at 16:40
  • @TanaySoni Start simple and only look for inefficiencies when you really need to. Do you have any metrics that would signal this approach as a potential bottleneck in your system? – Colin D Feb 20 '14 at 16:45
  • 1
    I'm trying to use mapping for pixels in a image processing applications. Considering the large data set( a typical image has millions of pixels), I am looking for a rather efficient approach. – dev Feb 20 '14 at 16:47
  • @ProblemFactory: Is BitMap implemented the same way? – dev Feb 20 '14 at 16:48
  • I believe you meant BiMap, then "probably" yes, you can download source and check it by yourself. – IProblemFactory Feb 21 '14 at 10:03