Get the range of values from the map in Java

Is it possible to get values that match a series of keys in a Java map Suppose I did,

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}

In this case, for the value of 4.0, I want to get 40 (key 4.2) and 20 (key 4.3) So I want to map all the values to the key 5.0 > = key > = 4.0 in the map Whether it can be realized through map or similar data structure

The map is large in size Or is there a better way to achieve the same goal with minimal complexity

Solution

You can use the implementation of navigablemap (example treemap) This approach deserves your special attention:

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

The underlying data structure of treemap is red and black trees. All complexity is abstracted by navigablemap interface, so it is very simple to use

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>