TreeMap删除大于某个特定键的所有键 [英] TreeMap removing all keys greater than a certain key
问题描述
在项目中,我需要删除所有键值大于某个键的对象(键类型为Date
,如果有关系的话).
In a project I need to remove all objects having key value greater than a certain key (key type is Date
, if it matters).
据我所知,用Java实现的TreeMap
是一棵红黑树,它是一个二进制搜索树.因此,删除子树时,我应该得到O(n)
.
但是我除了找到后视图并逐个删除需要O(logn)
的任何其他方法之外,找不到其他方法.
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)
.
实现此功能的任何好主意吗?我相信treeMap是要使用的正确的dataStructure,应该能够做到这一点.
Any good ideas implementing this function? I believe treeMap is the correct dataStructure to use and should be able to do this.
预先感谢
推荐答案
非常简单.而不是一个一个地删除条目,而是使用Map.clear()
删除元素.在代码中:
Quite simple. Instead of removing the entries one-by-one, use Map.clear()
to remove the elements. In code:
map.tailMap(key).clear();
这篇关于TreeMap删除大于某个特定键的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!