Search code examples
javasortedset

How to get the last 25 elements of a SortedSet?


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 :-(

Solution

  • You need a NavigableSet. Else you’ll have to do it inefficiently, iterating through the whole SortedSet and collecting elements into a Queue that you keep trimmed at 25 elements.