【问题标题】:How to get previous and next entries in TreeMap如何在 TreeMap 中获取上一个和下一个条目
【发布时间】:2017-09-18 02:41:22
【问题描述】:

我有一个排序的地图,我希望找到最接近的“之前”和“之后”条目的某些键,这些条目可以完全满足某些条件。

Entry findAfter(TreeMap map, Key key, Predicate p) {
    Entry e = map.higherEntry(key);
    while (e!=null && !p.test(e.getValue())
         e = map.higherEntry(e.getKey());
    return e;
}

这似乎效率低下,因为 O(logN) 中的更高条目。有没有更好的办法?

我希望 TreeMap 有可以在 O(1) 中工作的 map.nextEntry(e),但据我所知,没有。

【问题讨论】:

    标签: java treemap sortedmap


    【解决方案1】:

    检查:map.tailMap(key) 为您提供mapSortedSet 视图,其中包含所有大于或等于key 的键。然后map.tailMap(key).entrySet() 将为您提供Set<Map.Entry> 中所有条目的map,其键大于或等于key。根据javadocIteratorSet 之上按升序键顺序返回条目。

    所以也许这样的事情对你有用:

    Entry findAfter(TreeMap map, Key key, Predicate p) {
        for (Entry e : map.tailMap().entrySet()) {
            if (p.test(e.getValue() && 
                !e.getKey().equals(key))
                 return e;
        }
        return null;
    }
    

    一个对键子集的迭代器必须更接近O(1),而不是为每个连续更高的键搜索所有键。

    【讨论】:

      猜你喜欢
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2021-09-26
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多