4

As the title states, I am looking for a java collection keeping only the N last objects inserted into the collection. This FIFO collection does not need to implement random access or support changing N.

All collections I can find are either blocking (LinkedBlockingQueue) or of unlimited size (ArrayDeque). I found org.eclipse.jetty.util.ArrayQueue but as you could guess this brings quite an unwanted dependency on my project and also is very complicated since it support changing N so its not what I need.

Do you know if there is a way to have that with a quite common java library or do I have to write it myself?

jolivier
  • 7,380
  • 3
  • 29
  • 47
  • 3
    Check this out: http://stackoverflow.com/questions/7266042/java-ring-buffer – theglauber Aug 07 '12 at 16:58
  • What do you want to happen to the 'expired' elements? – Dan Gravell Aug 07 '12 at 17:01
  • See the answer of this question: http://stackoverflow.com/questions/422181/how-do-i-limit-the-number-of-entries-in-a-java-hashtable – YMomb Aug 07 '12 at 17:52
  • possible duplicate of [Size-limited queue that holds last N elements in Java](http://stackoverflow.com/questions/5498865/size-limited-queue-that-holds-last-n-elements-in-java) – om-nom-nom May 22 '13 at 13:25

3 Answers3

6

Check out Apache Commons CircularFifoBuffer

CircularFifoBuffer is a first in first out buffer with a fixed size that replaces its oldest element if full.

The removal order of a CircularFifoBuffer is based on the insertion order; elements are removed in the same order in which they were added. The iteration order is the same as the removal order.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
2

I would just write a wrapper class which contains a private Queue or Deque instance and a public insert method which behaves as you need if the queue is already full when the client tries to insert an extra member. The size could be passed in via the constructor, and any methods belonging to Queue or Deque which you need available but which already behave as you need you could simply forward to the private instance.

Bobulous
  • 12,967
  • 4
  • 37
  • 68
2

After Guava 15.0 there's EvictingQueue which come with a fixed size that replaces its oldest element if full.

sendon1982
  • 9,982
  • 61
  • 44