views:

111

answers:

2

I'd like to know what is there a better way to find the first value greater than an inputted value in a large SortedMap instead of looping through all values in my example below. Or if SortedMap is a the best structure to use for this.

Could this be achieved using google-collections? Thanks in advance

public class mapTest {
public static void main(String[] args) {

SortedMap<Double, Object> sortedMap = new TreeMap<Double, Object>();
    sortedMap.put(30d, "lala");     
    sortedMap.put(10d, "foo");
    sortedMap.put(25d, "bar");
    System.out.println("result: " + findFirstValueGreaterThan(sortedMap, 28d));
}

public static Object findFirstValueGreaterThan(SortedMap<Double, Object> sortedMap, Double value) {
    for (Entry<Double, Object> entry : sortedMap.entrySet()) {
        if (entry.getKey() > value) {
            // return first value with a key greater than the inputted value
            return entry.getValue();
        }
    }
    return null;
}
}
+4  A: 

It's all in the docs:

ceilingKey(K key)
Returns the least key greater than or equal to the given key, or null if there is no such key.

So,

findFirstValueGreaterThan(sortedMap, 28d)

should be

sortedMap.ceilingKey(28d)

Pay attention at difference between "greater than" and "greater than or equal to", though.

Nikita Rybak
@Nikita - strictly speaking, `ceilingKey` and similar methods are in the `NavigableMap` interface, not the `SortedMap` interface.
Stephen C
@Stephen Thanks, my bad. I'll leave the answer since TreeMap is mentioned in the question (and all standard SortedMap implementations are also NavigableMap implementations anyway).
Nikita Rybak
Thanks Nikita ..
paddydub
+2  A: 

This solution only requires SortedMap. Please note that tailMap typically doesn't create a new map, so it's fast.

public static <K extends Comparable<K>, V> V
        findFirstValueGreaterThan(SortedMap<K, V> map, K value) {
    Iterator<Entry<K, V>> it = map.tailMap(value).entrySet().iterator();
    if (it.hasNext()) {
        Entry<K, V> e = it.next();
        if (e.getKey().compareTo(value) > 0) {
            return e.getValue();
        } else if (it.hasNext()) {
            return it.next().getValue();
        }
    }
    return null;
}
Thomas Mueller
thanks thomas, ceilingKey looks better suited for my use case
paddydub
Sure. I just thought if there a way...
Thomas Mueller