Finding the first value more than in SortedMap

I would like to know that there is a better way to find the first value more than the entered value in the large SortedMap, and not iterate over all the values ​​in my example below. Or if SortedMap is the best framework to use.

Can this be done with 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;
}
}
+3
source share
2 answers

Everything in the docs:

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

So,

findFirstValueGreaterThan(sortedMap, 28d)

it should be

sortedMap.ceilingKey(28d)

Note the difference between greater than and greater than or equal to.

+6
source

SortedMap. , tailMap , .

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;
}
+2

Source: https://habr.com/ru/post/1765392/


All Articles