Search code examples
javacollectionstrimtreesetsortedset

Trimming a sorted set


I have a SortedSet (specifically a TreeSet) containing updates. An update is something like an SVN commit, Facebook wall post, new Trac ticket, etc. I'm storing these in a SortedSet because:

  • Sorted: The updates need to be sorted by date, descending.
  • Set: When fetching the latest updates from an update source, I'll usually receive updates that are already in the set.

Now, after a while the set will grow really huge, so I'd like to remove anything but the first X items from the set (because others won't be displayed anyway). How can I do this, since it's not a List?


Solution

  • While(mySet.size() > limit) {
      mySet.remove(mySet.last());
    }