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?
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.
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.
In these cases, we can use Collections such as list, set, etc. to insert multiple values into the same key in HashMap.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With