【问题标题】:Finding the first value greater than in a SortedMap在 SortedMap 中查找大于的第一个值
【发布时间】:2011-04-14 00:11:37
【问题描述】:

我想知道有什么更好的方法可以在大型 SortedMap 中找到大于输入值的第一个值,而不是在下面的示例中循环遍历所有值。或者,如果 SortedMap 是用于此目的的最佳结构。

这可以使用 google-collections 来实现吗? 提前致谢

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

【问题讨论】:

    标签: java guava sortedmap


    【解决方案1】:

    此解决方案只需要 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;
    }
    

    【讨论】:

    • 感谢 thomas,ceilingKey 看起来更适合我的用例
    【解决方案2】:

    这一切都在文档中:

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

    所以,

    findFirstValueGreaterThan(sortedMap, 28d)
    

    应该是

    sortedMap.ceilingKey(28d)
    

    不过,请注意“大于”和“大于或等于”之间的区别。

    【讨论】:

    • 严格来说ceilingKey等类似方法在NavigableMap接口中,而不是SortedMap接口中。
    • @Stephen 谢谢,我的错。我会留下答案,因为问题中提到了 TreeMap(并且所有标准的 SortedMap 实现也是 NavigableMap 实现)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多