2012-02-17 16 views
3

是否可以獲取與Java Map中的一系列鍵匹配的值。假設我有,從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)。所以我想獲得映射到地圖中的關鍵5.0 >= key>=4.0的所有值。是否可以通過Map或類似的數據結構來做到這一點。

地圖的大小是巨大的。或者還有其他更好的方式來以最小的複雜性實現這一目標嗎?

+2

我只是希望你的'Key'不是基於'Double'或'Float' ...這將導致由於浮點運算問題造成的故障 – amit 2012-02-17 10:08:24

+2

也許使用'java.util.NavigableMap',看它在文檔中查看並檢查它是否支持你所需要的。 – Jesper 2012-02-17 10:12:17

回答

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); 

的樹形圖中的基礎數據結構是紅色和黑色的樹,所有的複雜性是由NavigableMap的接口抽象從而非常簡單易用。

+1

+1向我介紹'NavigableMap'。謝謝! – Vic 2012-02-17 10:20:13