从Java中的Map中获取值的范围
发布时间:2020-12-15 08:47:42 所属栏目:Java 来源:网络整理
导读:是否有可能获得与 Java Map中的一系列键匹配的值.假设我有, MapKey,Value //size 10,000Key - 9.0,9.1,9.5,4.2,4.3,6.1,6.6Value - 10,20,30,40,60,10 ArrayList alMatch = {1.0,4.0,6.0} 在这种情况下,对于值4.0,我想得到40(关键4.2)和20(关键4.3).所以我希
|
是否有可能获得与
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,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或类似的数据结构来实现. 地图的大小很大.或者是否有其他更好的方法以最小的复杂性实现相同的目标. 解决方法
您可以使用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接口抽象,因此使用起来非常简单. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
