Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection that loses oldest elements on add()

Tags:

java

I'm looking for a Java class that implements Collection and loses oldest elements when I add() a new one, if total number of elements is bigger than X. Does it exist or I have to implement it myself?

I need a thread-safe one.

like image 605
yegor256 Avatar asked Jul 31 '14 13:07

yegor256


3 Answers

Apart from Linkedhasmap if you are looking for list type solution, Google guava has EvictingQueue. And for thread safety you must wrap it in a synchronized wrapper (Queues#synchronizedQueue).

EvictingQueue<String> q = EvictingQueue.create(3);
Queue<String> syncQ =  Queues.synchronizedQueue(q);
syncQ.add("one");
syncQ.add("two");
syncQ.add("three");
syncQ.add("four");
System.out.println(q); // Prints [two, three, four]
like image 56
Syam S Avatar answered Oct 29 '22 10:10

Syam S


You can use the LinkedHashMap to do precisely that, quoting the Javadoc:

// Sample use: this override will allow the map to grow up to 100 entries and then delete the 
// eldest entry each time a new entry is added, maintaining a steady state of 100 entries.

 private static final int MAX_ENTRIES = 100;

 protected boolean removeEldestEntry(Map.Entry eldest) {
    return size() > MAX_ENTRIES;
 }

for thread safe-ness you can wrap it using Collections.synchronizedmap().

like image 21
rsp Avatar answered Oct 29 '22 11:10

rsp


CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its
oldest element if it is full.

like image 45
David Pullar Avatar answered Oct 29 '22 11:10

David Pullar