TreeMap removing all keys greater than a certain key

三世轮回 提交于 2019-12-12 11:38:43

问题


In a project I need to remove all objects having key value greater than a certain key (key type is Date, if it matters).

As far as I know TreeMap implemented in Java is a red-black tree which is a binary search tree. So I should get O(n) when removing a subtree.
But I can't find any method to do this other than making a tail view and remove one by one, which takes O(logn).

Any good ideas implementing this function? I believe treeMap is the correct dataStructure to use and should be able to do this.

thanks in advance


回答1:


Quite simple. Instead of removing the entries one-by-one, use Map.clear() to remove the elements. In code:

map.tailMap(key).clear();



回答2:


public class TreeMapDemo {
    public static void main(String[] args) {
            // creating maps
            TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
            SortedMap<Integer, String> treemapincl = new TreeMap<Integer, String>();

            // populating tree map
            treemap.put(2, "two");
            treemap.put(1, "one");
            treemap.put(3, "three");
            treemap.put(6, "six");
            treemap.put(5, "five");

            System.out.println("Getting tail map");
            treemap.tailMap(3).clear();

            System.out.println("Tail map values: " + treemapincl);
            System.out.println("Tree map values: " + treemap);
     }
}

This will remove the elements in the tree map.



来源:https://stackoverflow.com/questions/22976970/treemap-removing-all-keys-greater-than-a-certain-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!