是否可以获取与Java Map中的一系列键匹配的值。假设我有,
Map<Key,Value> //size 10,000
Key - 9.0, 9.1, 9.5, 4.2, 4.3, 6.1, 6.6
Value - 10 , 20 , 30 , 40 , 20 , 60 , 10
ArrayList alMatch = {1.0,4.0,6.0}
在这种情况下,对于值4.0,我想得到40(关键4.2)和20(关键4.3)。所以我希望将所有值映射到Map中的键5.0 >= key>=4.0
。是否可以通过Map或类似的数据结构来实现。
地图的大小很大。或者还有其他更好的方法来实现同样的复杂性。
答案 0 :(得分:7)
您可以使用NavigableMap的实现(示例TreeMap)。这种方法特别值得您关注:
/**
* Returns a view of the portion of this map whose keys range from
* {@code fromKey} to {@code toKey}. If {@code fromKey} and
* {@code toKey} are equal, the returned map is empty unless
* {@code fromExclusive} and {@code toExclusive} are both true. The
* returned map is backed by this map, so changes in the returned map are
* reflected in this map, and vice-versa. The returned map supports all
* optional map operations that this map supports.
*
* <p>The returned map will throw an {@code IllegalArgumentException}
* on an attempt to insert a key outside of its range, or to construct a
* submap either of whose endpoints lie outside its range.
*
* @param fromKey low endpoint of the keys in the returned map
* @param fromInclusive {@code true} if the low endpoint
* is to be included in the returned view
* @param toKey high endpoint of the keys in the returned map
* @param toInclusive {@code true} if the high endpoint
* is to be included in the returned view
* @return a view of the portion of this map whose keys range from
* {@code fromKey} to {@code toKey}
* @throws ClassCastException if {@code fromKey} and {@code toKey}
* cannot be compared to one another using this map's comparator
* (or, if the map has no comparator, using natural ordering).
* Implementations may, but are not required to, throw this
* exception if {@code fromKey} or {@code toKey}
* cannot be compared to keys currently in the map.
* @throws NullPointerException if {@code fromKey} or {@code toKey}
* is null and this map does not permit null keys
* @throws IllegalArgumentException if {@code fromKey} is greater than
* {@code toKey}; or if this map itself has a restricted
* range, and {@code fromKey} or {@code toKey} lies
* outside the bounds of the range
*/
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
K toKey, boolean toInclusive);
TreeMap的底层数据结构是红色和黑色树,所有复杂性都由NavigableMap界面抽象,因此使用起来非常简单。