Retrieve all entries from Map<Integer, String> with keys in certain range

你离开我真会死。 提交于 2019-12-24 00:52:45

问题


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.

What Map implementation is suitable for these needs ?


回答1:


Use a TreeMap, which implements NavigableMap supplying a subMap method returning a view of the map with only keys in your range. To get the values, of course you call values() on the result.

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.




回答2:


You are probably looking for a NavigableMap. However, you can't use HashMap to create one, because the map would have to be a SortedMap. Consider using TreeMap instead.




回答3:


TreeMap will provide a sorted list of keys. You would then need to trim the list to get your range of values.



来源:https://stackoverflow.com/questions/8226634/retrieve-all-entries-from-mapinteger-string-with-keys-in-certain-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!