Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get values for keys within a range in Java

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?

like image 563
Emil Avatar asked Aug 19 '10 08:08

Emil


People also ask

Can you get a key from a value Java?

Obtaining a key for a value is supported by the getKey() method.

What does .values do in Java?

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.

How do you get all keys of a map as a list in Java?

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 .


3 Answers

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.

like image 166
polygenelubricants Avatar answered Oct 26 '22 17:10

polygenelubricants


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.

like image 21
helios Avatar answered Oct 26 '22 17:10

helios


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());
}
like image 31
Maurice Perry Avatar answered Oct 26 '22 19:10

Maurice Perry