5

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

ernd enson
  • 1,764
  • 1
  • 14
  • 29
Hongxiang Qiu
  • 63
  • 1
  • 3

2 Answers2

14

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

map.tailMap(key).clear();
tbodt
  • 16,609
  • 6
  • 58
  • 83
  • This would remove the subtree, more or less? – Tyler Apr 10 '14 at 01:27
  • @Tyler The title says "removing all keys greater than a certain key", and that's what this does. – tbodt Apr 10 '14 at 01:27
  • 2
    But will it run in *O(N)* time? *That's* the question. – user207421 Apr 10 '14 at 01:31
  • Is there any other way to do this with a `SortedMap`? – tbodt Apr 10 '14 at 01:34
  • That's not the question either. The question is how to do it in O(N). The answer may well be that you can't. – user207421 Apr 10 '14 at 01:38
  • @EJP from the source code it seems clearing is just setting root=NULL, so including GC runtime, it should be O(N) if fixAfterDeletion is called only once.. I will do an experiment on this. – Hongxiang Qiu Apr 10 '14 at 01:44
  • @tbodt Thank you for your answer. I don't quite understand how the opertaion on tailMap will callback the origin map. Will it call the fixAfterDeletion function of the origin map after clearing? – Hongxiang Qiu Apr 10 '14 at 01:46
  • @HongxiangQiu That's the code for clearing the entire tree. Clearing a subtree is elsewhere in the code, and it can't be just a matter of setting root to null, as the red-black properties have to be preserved. There must be rotations. – user207421 Apr 10 '14 at 01:54
  • @EJP yes you are right. i didnt look into the return type which is a sub*tree. – Hongxiang Qiu Apr 10 '14 at 18:16
0
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.

Eiko
  • 25,601
  • 15
  • 56
  • 71