I need a Map<Integer,String> with a major need to do fast retrievals of values by key. However I also have the need to retrieve List of all entries (key, value pairs) whose keys are in range (n1 to n2). However, No sorting required in the list.
The map would hold atleast 10,000 such entries.
I initially thought of using TreeMap but that doesn’t help with faster retrievals(O(log n) for get() operations). Is it possible to get a list of entries from HashMap whose keys are in range n1 to n2 ?
What would be my best bet to go with ?
The two implementations of
NavigableMap(which allow you to retrieve sub-maps or subsets based on key ranges) areTreeMapandConcurrentSkipListMap, both of which offer O(log n) access time.Assuming you require O(1) access time as per a regular
HashMap, I suggest to implement your own (inefficient) “key range” methods. In other words, sacrifice the performance of the key-range operation for the improved access time you achieve with a regularHashMap. There isn’t really another way around this:NavigableMapmethods are inherently dependent on the data being stored in a sorted fashion which means you will never be able to achieve O(1) access time.