Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeMap removing all keys greater than a certain key

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

like image 572
Hongxiang Qiu Avatar asked Apr 10 '14 01:04

Hongxiang Qiu


1 Answers

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

map.tailMap(key).clear();
like image 148
tbodt Avatar answered Nov 15 '22 03:11

tbodt