0

I have a Map having duplicate values. I now want to get the key using value without iterating through all the Map.Entries. I have more than 500 entries in the map. I do not want to iterate the whole map each time.

I thought of using BiMap of google collections. But, BiMap does not support duplicate keys. Could anyone suggest on what other thirdparty library can be used to solve this?

Update: The map contains duplicate values and it's loaded from a text file containing key value pairs.

John
  • 541
  • 3
  • 6
  • 19
  • 11
    According to the Javadoc for `Map`: "If the map previously contained a mapping for the key, the old value is replaced by the specified value". Soo... are you sure it supports duplicate keys ? – Radu Murzea Feb 21 '13 at 08:50
  • Keys are unique; consider using a collection of values. – McDowell Feb 21 '13 at 08:51
  • @SoboLAN I have the map with duplicate values. Map is loaded from a text file having key value pairs. When I use copyOf method of BiMap, it does not allow for reason of having duplicate values. – John Feb 21 '13 at 08:55
  • 1
    @John So you mean duplicate values and not duplicate keys right ? then please edit your question accordingly. – Apurv Feb 21 '13 at 09:16

2 Answers2

4

You could use a ListMultimap and then use Multimaps.invertFrom() to get the inverse mapping.

Edward Samson
  • 2,395
  • 2
  • 26
  • 39
1

I have a Map

...well, there's your problem! It sounds like the data doesn't quite fit the limitations of a BiMap. Consider maintaining a different ordered collection of your data encapsulated as tuples (or a pair of ordered collections).

Tim Bender
  • 20,112
  • 2
  • 49
  • 58