将 TreeMap 修剪为 n 个条目
我有一个已排序的 TreeMap,我想删除除前 10 个元素之外的所有元素。有什么方法可以做到这一点?我考虑过在地图大小大于 10 时从地图末尾删除元素,但我不知道该怎么做。我可以转换为列表然后再转换回来吗?
谢谢
I have a sorted TreeMap, and I want to remove all but the first 10 elements. What is a way to do this? I have considered removing elements from the end of the map while the map size is greater than 10, but I don't know how to do that. Could I convert to a List and then back?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
HashMap
没有开头或结尾——它们是无序的。迭代项目的顺序与插入项目的顺序完全无关。如果您可以改用 LinkedHashMap,那么该类实际上会保留项目插入的顺序。然后,您可以简单地迭代entrySet()
,在迭代前 10 个项目后,对每个项目调用迭代器上的remove()
。HashMap
s don't have a beginning or an end -- they're unordered. The order in which you iterate over the items will be totally unrelated to the order in which you inserted the items. If you can use a LinkedHashMap instead, that class does, in fact, preserve the order in which the items are inserted. Then you could simply iterate overentrySet()
, callingremove()
on the iterator for each item after you've iterated over the first ten.这是一个想法。也许制作一个大小限制为 10 个元素的地图类,并以这种方式复制/构造有限的地图段:
通过向有限大小的地图添加 100 个元素来测试它,一次通过多次 put() 调用,一次使用构造函数:
转储映射,无论您一次添加一个元素,还是使用构造函数构建映射,您都只有 10 个元素的映射:
1->101
2->102
3->103
4->104
5->105
6->106
7->107
8->108
9->109
10->110
1->201
2->202
3->203
4->204
5->205
6->206
7->207
8->208
9->209
10->210
我没有在防御性编程、检查空值之类的事情上投入任何时间。这里的想法是我不知道也不关心你的原始地图是什么。链接地图。树图。常规地图。无论它返回的元素的顺序如何,都定义了“前 10 个元素”的含义,而我的地图类将仅存储前 10 个元素,并忽略之后的任何元素。现在您已经有了前 10 个,无论这对您的地图意味着什么。
Here's a thought. Maybe make a map class that is limited in size to 10 elements, and copy/construct your limited map segment that way:
Test it by adding 100 elements to the limited-size map, once by multiple put() calls, and once by using the constructor:
Dump the maps, and you only have maps of 10 elements, whether you added the elements one at a time, or built the map with a constructor:
1->101
2->102
3->103
4->104
5->105
6->106
7->107
8->108
9->109
10->110
1->201
2->202
3->203
4->204
5->205
6->206
7->207
8->208
9->209
10->210
I haven't invested any time in defensive programming, checking for nulls, that sort of thing. The idea here is that I don't know or care what your original map is. Linked Map. Tree Map. Regular Map. Whatever order it returns the elements defines what you mean by the "first 10 elements", and my map class will only store those first 10, and ignore any after that. Now you have your first 10, whatever that means for your map.