How to get the last 25 elements of a 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).

NavigableSet<T> set = new TreeSet<T>();
// add elements
set.descendingIterator() // iterate over the last n entires as needed

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.

Tags:

Java

Sortedset