[英]Retrieve all entries from Map<Integer, String> with keys in certain range
I need to have a HashMap< Integer, String> which can serve fast operations for retrieving a list of all entries whose keys are in a certain integer range besides, getting values from map based on keys. 我需要有一个HashMap <Integer,String>,它可以提供快速操作来检索键在某个整数范围内的所有条目的列表,此外,还可以基于键从映射中获取值。
What Map
implementation is suitable for these needs ? 哪种
Map
实现适合这些需求?
You are probably looking for a NavigableMap
. 您可能正在寻找
NavigableMap
。 However, you can't use HashMap
to create one, because the map would have to be a SortedMap
. 但是,您不能使用
HashMap
创建地图,因为地图必须是SortedMap
。 Consider using TreeMap
instead. 考虑改用
TreeMap
。
TreeMap
will provide a sorted list of keys. TreeMap
将提供键的排序列表。 You would then need to trim the list to get your range of values. 然后,您需要修剪列表以获取值的范围。
Use a TreeMap
, which implements NavigableMap
supplying a subMap method returning a view of the map with only keys in your range. 使用
TreeMap
,该树实现NavigableMap
提供了subMap方法,该方法返回仅包含您范围内的键的地图视图。 To get the values, of course you call values()
on the result. 要获取值,您当然可以在结果上调用
values()
。
If you have an existing Map
whose keys implement Comparable
, you can construct a TreeMap
from it by calling new TreeMap(existingMap)
, but it will likely be more efficient to create it as a TreeMap
from the start. 如果您有一个现有的
Map
其键实现Comparable
,则可以通过调用new TreeMap(existingMap)
从其构造TreeMap
,但是从一开始将其创建为TreeMap
可能会更有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.