java如何使用LinkedHashMap获取子映射?
目前,我正在使用TreeMap
来存储一些x和y坐标,但是与ArrayList
或HashMap
相比,迭代非常慢。我之所以使用它,是因为我需要subMap()
方法,这样我就可以在确定的范围内获得X值,即使精确的X值(键)不存在
LinkedHashMap
的速度几乎与HashMap
相同,我可以按插入顺序迭代键(我需要插入顺序或比较器顺序,就像在TreeMap中那样),但我没有submap()
方法。在树状图中,我可以快速生成子图
是否有任何数据结构或某种方式可以比TreeMap更快地存储有序值(通过插入顺序或比较器),即使精确值不在映射中,也可以在一定范围内获取子映射?我的意思是,也许我想要2到25之间的值,但是2不存在,最近的值是3,所以它将返回一个从3到25的子映射。或者以某种方式将此功能添加到LinkedHashMap
# 1 楼答案
今天我终于找到了问题的答案。经过几次测试
HashMap
,LinkedHashMap
和TreeMap
比ArrayList
慢得多,我想使用它们只是为了创建subMaps()
。因此,我创建了一个扩展ArrayList
的新类,它给了我非常好的性能,在this答案的帮助下,我创建了一种通过值而不是索引获取子列表的快速方法。以下是完整的课程:PointValue
只是一个包含x和y坐标的类。现在我只要调用subList()
传递我想要的x坐标范围。在我的例子中,插入顺序也被排序,这对于使用Collections.binarySearch()
很重要# 2 楼答案
听起来你需要一个树形图,它的迭代速度不比LinkedHashMap慢多少,并且可以实现你真正想要的。由于HashMap是无序的,所以subMap没有任何意义