[英]Need a Map for faster retrievals by key & for getting a list of entries with keys in some range
I need a Map<Integer,String>
with a major need to do fast retrievals of values by key
. 我需要一个
Map<Integer,String>
,主要需要通过key
快速检索值。 However I also have the need to retrieve List
of all entries ( key
, value
pairs) whose keys are in range (n1 to n2). 但是,我还需要检索其键值在(n1到n2)范围内的所有条目(
key
, value
对)的List
。 However, No sorting required in the list. 但是,列表中不需要排序。 The map would hold atleast 10,000 such entries.
该地图将包含至少10,000个此类条目。
I initially thought of using TreeMap
but that doesn't help with faster retrievals(O(log n) for get() operations). 我最初想到使用
TreeMap
但是这对于更快的检索(get()操作的O(log n))没有帮助。 Is it possible to get a list of entries from HashMap whose keys are in range n1 to n2 ? 是否可以从HashMap中获取键范围在n1到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) are TreeMap
and ConcurrentSkipListMap
, both of which offer O(log n) access time. NavigableMap
的两个实现(允许您根据键范围检索子图或子集)是TreeMap
和ConcurrentSkipListMap
,它们都提供O(log n)访问时间。
Assuming you require O(1) access time as per a regular HashMap
, I suggest to implement your own (inefficient) "key range" methods. 假设您需要按照常规
HashMap
访问时间为O(1),建议您实现自己的(效率低下的)“键范围”方法。 In other words, sacrifice the performance of the key-range operation for the improved access time you achieve with a regular HashMap
. 换句话说,牺牲键范围操作的性能来缩短使用常规
HashMap
获得的访问时间。 There isn't really another way around this: NavigableMap
methods 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. 真的没有其他方法可以解决:
NavigableMap
方法固有地依赖于以排序方式存储的数据,这意味着您将永远无法获得O(1)访问时间。
How close are the keys distributed? 密钥分布多近? For 10000 elements, equally distributed over 20 000 possibilities like 0 to 19999, I could imagine a search for elements from 4 to 14 could be fine.
对于10000个元素(均等地分布在2万种可能性中,如0到19999),我可以想象搜索4到14个元素可能很好。 You would miss at a 50% rate.
您会以50%的速度错过。
I wonder why TreeMap doesn't help with faster retrievals (O(log n) for get() operations)? 我不知道为什么TreeMap无法帮助更快地进行检索(对于get()操作,为O(log n))?
If you have Tree, with smaller values Left, and bigger ones right, you could return big parts of subtrees. 如果您有Tree,且Left的值较小,而right的值较大,则可以返回子树的大部分。 Need it be Map and List?
需要地图和列表吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.