Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java collection keeping only n last inserted members

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?

like image 574
jolivier Avatar asked Dec 27 '22 19:12

jolivier


1 Answers

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.

like image 85
Brian Agnew Avatar answered Jan 11 '23 23:01

Brian Agnew