问题
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