如何获取 SortedSet 的最后 25 个元素?
在 Java 中,我有一个可能有 100,000 个元素的 SortedSet。 我想高效、优雅地获取最后 25 个元素。 我有点疑惑。
为了获得前 25 个元素,我会迭代并在 25 个元素后停止。 但我不知道如何以相反的顺序迭代。 有任何想法吗?
SortedSet<Integer> summaries = getSortedSet();
// what goes here :-(
In Java I have a SortedSet that may have 100,000 elements. I would like to efficiently and elegantly get the last 25 elements. I'm a bit puzzled.
To get the first 25 I'd iterate and stop after 25 elements. But I don't know how to iterate in reverse order. Any ideas?
SortedSet<Integer> summaries = getSortedSet();
// what goes here :-(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您需要一个
NavigableSet
。 否则,您将不得不低效地执行此操作,迭代整个SortedSet
并将元素收集到Queue
中,并将其修剪为 25 个元素。You need a
NavigableSet
. Else you’ll have to do it inefficiently, iterating through the wholeSortedSet
and collecting elements into aQueue
that you keep trimmed at 25 elements.SortedSet
的设计假设一个非常简单的迭代模型,仅向前,因此找到前 n 个条目很容易,但找到最后一个条目需要通过迭代器进行昂贵的读取,维护最后一个的窗口n 个条目。NavigableSet
在 1.6 中添加解决了这个问题(并且 1.4 TreeSet 中唯一的 SortedSet 实现实现了它,因此它可能是您的替代品)。SortedSet
<T>
was designed assuming a very simple iteration model, forward only, thus finding the top n entries is easy but finding the last would require an expensive read through the iterator maintaining a window of the last n entries.NavigableSet
<T>
adding in 1.6 solves this (and the only SortedSet implementation from 1.4 TreeSet implements it so it is likely to be a drop in replacement for you).反转排序并取出前 25 项。 然后您可以反转那些高效的项目,因为它只有 25 个项目。
布鲁斯
Reverse your sort and take the first 25 items. You can then reverse those which will be efficient as its only 25 items.
Bruce
不同的数据结构更适合此操作。
这不是一种优雅的方式,也不是非常有效,但假设 SortedSet 按升序排列,您可以获取 Last() 项并将其删除,将其存储在另一个列表中,然后重复 25 次。 然后您将不得不再次将这些元素放回去!
A different data structure would be more appropriate for this operation.
This is not an elegant way or very efficient, but assuming the SortedSet is in ascending order you could get the Last() item and remove it, storing it in another list, and repeat 25 times. You would then have to put these elements back again!
将 Set 放入 List 中并使用 subList()。 我不确定创建列表的性能如何,因此您必须运行一些测试。 不过,这肯定会让编码变得容易。
Throw the Set into a List and use subList(). I'm not sure how performant it is to create the List, so you'd have to run some tests. It'd certainly make the coding easy though.
https://github.com/geniot/indexed-tree-map
你可能想要看一下 indexed-tree-map 中的 "nofollow noreferrer">IndexedTreeMap
使用精确(size-25) 无需迭代即可获取索引处的元素。
https://github.com/geniot/indexed-tree-map
You may want to take a look at IndexedTreeMap in indexed-tree-map
Use exact(size-25) to get to the element at index without iteration.
我假设这在您的项目中不太可能有任何实际用途,但值得注意的是,您可能只是能够以相反的方向对列表进行排序:)
I'm assuming that this is unlikely to be of any real-life use in your project, but it's worth noting that you might simply be able to have the list sorted in the opposite direction instead :)