2

I have a situation where many many keys are pointing to a single value. The situation arises from a service locator pattern that I am implementing such that -

  • each method in an interface is represented as a signature string
  • All such signatures of a single interface are used as keys
  • The value being the full canonical name of the implementation class

Thus my need is to retrieve a single value when user requests any of the matching keys.

In a sense I need an opposite of MultiMap from Guava .

I am looking for the most optimized solution there is since my keys are very similar though unique for a specific value and I am not sure if using a generic Map implementation like HashMap is efficient enough to handle this case.

e.g. all the below signatures

==============

_org.appops.server.core.service.mocks.MockTestService_testOperationThree _org.appops.server.core.service.mocks.MockTestService_getService _org.appops.server.core.service.mocks.MockTestService_start _org.appops.server.core.service.mocks.MockTestService_testOperationTwo_String_int _org.appops.server.core.service.mocks.MockTestService_getName _org.appops.server.core.service.mocks.MockTestService_shutdown _org.appops.server.core.service.mocks.MockTestService_testOperationOne_String

=======

Point to a single class i.e. org.appops.server.core.service.mocks.MockTestServiceImpl and I am anticipating hundreds of such classes (values) and thousands of such similar signatures (keys) .

In case there is no optimized way I could always use a HashMap with replicated values for each group of keys which I would like to avoid.

Ideally I would like to use a ready utility from Guava.

Gautam
  • 1,030
  • 13
  • 37
  • This question is very similar to http://stackoverflow.com/questions/1062960/map-implementation-with-duplicate-keys but is different since I have a single value (not a collection) for multiple unique keys – Gautam May 22 '14 at 12:54
  • To be precise I am looking for the most efficient data structure to manage this. I am aware a HashMap can be used with duplicate values. thanks. – Gautam May 22 '14 at 13:03

1 Answers1

6

HashMap is actually what you need, and the issue is that you misunderstand what it does.

In case there is no optimized way I could always use a HashMap with replicated values for each group of keys which I would like to avoid.

HashMap does not store a copy of the value for each key mapping to that value. HashMap stores a reference to the Java object. It's always the same cost. A HashMap<Integer, BigExpensiveObject> where every key is mapped to the same BigExpensiveObject takes exactly the same amount of memory as a HashMap<Integer, Integer> where every key is mapped to the same Integer. The only memory difference in the whole program would be the memory difference between one BigExpensiveObject and one Integer.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413