Suppose I have a map in Java which looks like this:
{
39:"39 to 41",
41:"41 to 43",
43:"43 to 45",
45:">=45"
}
If the keys are in sorted order(either using treemap or linkedhashmap).Now if i try to get a value which is >=39 and <41.Then I should get the String "39 to 41".How do I do this efficiently?
Obtaining a key for a value is supported by the getKey() method.
Example 1: Java HashMap values() Here, the values() method returns a view of all the values present in the hashmap. The values() method can also be used with the for-each loop to iterate through each value of the hashmap.
Use keySet() to Get a Set of Keys From a HashMap in Java The simplest way to get the keys from a HashMap in Java is to invoke the keySet() method on your HashMap object. It returns a set containing all the keys from the HashMap .
It looks like you want more than a SortedMap
; you want a NavigableMap
! Specifically you can use the floorKey
operation.
Here's an example:
NavigableMap<Integer,String> map = new TreeMap<Integer, String>(); map.put(0, "Kid"); map.put(11, "Teens"); map.put(20, "Twenties"); map.put(30, "Thirties"); map.put(40, "Forties"); map.put(50, "Senior"); map.put(100, "OMG OMG OMG!"); System.out.println(map.get(map.floorKey(13))); // Teens System.out.println(map.get(map.floorKey(29))); // Twenties System.out.println(map.get(map.floorKey(30))); // Thirties System.out.println(map.floorEntry(42).getValue()); // Forties System.out.println(map.get(map.floorKey(666))); // OMG OMG OMG!
Note that there are also ceilingKey
, lowerKey
, higherKey
, and also …Entry
instead of …Key
operations as well which returns a Map.Entry<K,V>
instead of just the K
.
Try Java 6 java.util.NavigableMap
. http://download.oracle.com/javase/6/docs/api/java/util/NavigableMap.html.
In special use floorKey
/floorEntry
.
By example: floorKey(40)
should return 39
. floorEntry would return the value you are looking for.
With a sorted map, you could do something like that:
SortedMap<Integer,String> head = map.headMap(value+1);
if (head.isEmpty()) {
return null;
} else {
return head.get(head.lastKey());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With