从特定位置(键)

时间:2015-05-06 10:13:46

标签: java

我需要的是从n个条目向后请求的键的值的子列表。由于地图非常大,我想知道是否" floorKey"是完成此任务的最有效方法。

这段代码写得更快吗?

        TreeMap qMap = new TreeMap();
        Object key = "startKey";

        for (int i=0; i<2000; i++) {
            key = qMap.floorKey(key);
        }

        // get a collection holding last 2000 history objects at startkey
        Collection neededValues = qMap.subMap(key, "startKey").values(); 

编辑:

根据@ Thilo的回答,我做了一个快速的干燥测试,是的,他的方法更快:

public static void main(String[] args) {
        TreeMap a = new TreeMap();
        for (int i=0; i<5000000; i++) a.put("a"+i, i);

        int i=2000;
        Object dummy;

        System.out.println("start a");
        long start = new Date().getTime();
        NavigableSet keys = (NavigableSet) a.navigableKeySet().headSet("a"+670812); // some random position
        Iterator goBack = keys.descendingIterator();

        while (goBack.hasNext() && i>0) {
            dummy = goBack.next();
            i--;
        }

        System.out.println("run a " + (new Date().getTime() - start));
        System.out.println("start b");

        start = new Date().getTime();
        Object key = "a"+670812;
        for (i=0; i<2000; i++) {
            key = a.floorKey(key);
        }

        Object dummy2 = a.subMap(key, "a" + 670812).values();
        System.out.println("run b " + (new Date().getTime() - start));
    }

打印

start a
run a 6
start b
run b 7

1 个答案:

答案 0 :(得分:2)

您可以从TreeMap获得NavigableSet

像(没试过)的东西

NavigableSet<T> keys = qMap.navigableKeySet().headSet("startKey");
Iterator<T> goBack = keys.descendingIterator();

不确定它是否会对性能产生很大影响。至少它似乎摆脱了你对floorKey的2000次调用。