Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Map with a variable key length in Java world?

Tags:

java

hashmap

map

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?

like image 379
user1081596 Avatar asked Jan 16 '12 14:01

user1081596


People also ask

Can a key in HashMap have multiple values?

In the above code, different combinations that make up a number are put under the same key in the HashMap . The HashMap uses the Integer class and the ArrayList of Strings. The Strings are different combinations, for example, the string “1+3” results in 4, which is the key value for that string.

Can Java Map have multiple values?

Java has several implementations of the interface Map, each one with its own particularities. However, none of the existing Java core Map implementations allow a Map to handle multiple values for a single key.

How do I store multiple values in one HashMap key?

In these cases, we can use Collections such as list, set, etc. to insert multiple values into the same key in HashMap.


2 Answers

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.

like image 174
Peter Lawrey Avatar answered Oct 06 '22 10:10

Peter Lawrey


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.

like image 29
Sergey Kalinichenko Avatar answered Oct 06 '22 08:10

Sergey Kalinichenko