6

I need a Map but when I call get(key, n) it should should return not only all the records with the searched key value, but also all where the n last significant bits of the key are the same as the search key (e.g. applying something like key&(1<<(n+1)-1)).

Is there something like this already implemented in Java?

user1081596
  • 917
  • 1
  • 9
  • 16
  • Why not just make the actual key just the n least significant bits of the computed key? – President James K. Polk Jan 16 '12 at 14:02
  • @GregS: I believe the OP wants `n` to be given on the fly, per query. – amit Jan 16 '12 at 14:03
  • Clearly something as specific as this isn't available in the standard library. The question is: can't you just use the n last significant bits as the key and a list as the value? Why specify a key that you can't actually use? – Viruzzo Jan 16 '12 at 14:03
  • Given how unusual these requriements are it's extremely unlikely such a thing is already available – Dónal Jan 16 '12 at 14:03
  • 1
    @GregS - The getter can specify any value of n from 1 to N, so you'd have to store N-1 entries for each key of N bits if you did it that way. – Daniel Earwicker Jan 16 '12 at 14:04
  • You could possibly iterate through a treemap? There is a solution which I think is similar to what you're asking here: http://stackoverflow.com/questions/537921/efficiently-iterate-through-all-matching-keys-in-a-hashmap - specifically see http://stackoverflow.com/a/537957/201648 – Aaron Newton Jan 16 '12 at 14:08
  • My first port of call is always http://commons.apache.org/collections/apidocs/ but unfortunately there's nothing like this there. The closest would be the MultiKeyMap but this is presumably not what you want (if you want run-time derived number of bits for the key). – wmorrison365 Jan 16 '12 at 14:22

2 Answers2

10

Not quite, but you can use a NavigableMap.subMap to implement this. e.g.

NavigableMap<Integer, Value> map =
int keyBase = key & ~((1 << n)-1);
Map<Integer, Value> subMap = map.subMap(keyBase, true, keyBase + (1 << n), false);

If you want to search based on the lowest bits instead of the highest bits, you have to reverse the bits before adding and searching. This will group together the lowest bit, second lowest bit then third lowest bit etc.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

HashMap is not going to do it, but a TreeMap could.

You will need to normalize and reverse your keys (i.e. decide how many bits you'd like to keep, and reverse the bits to make the less significant bits to be your most significant). Then you can strip the less significant bits (formerly the most significant bits) from your keys, and use range searches of the tree map to find your answer.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523