2012-02-17 31 views
3

Javaマップのキーの範囲に一致する値を取得できますか?この場合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にマッピングする必要があります。これはマップや同様のデータ構造を使って行うことが可能ですか?

地図のサイズが大きいです。あるいは、最小限の複雑さで同じことを達成するための他のより良い方法があります。

+2

'Key'が' Double'または 'Float'に基づいていないことを期待しています...これは浮動小数点演算の問題による失敗につながります – amit

+2

' java.util.NavigableMap'それが必要なものを正確にサポートしているかどうかを確認してください。私に「NavigableMap」を導入するための+1は – Jesper

答えて

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のインタフェースによって抽象化されます。

+1

です。ありがとう! – Vic

関連する問題