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.
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]
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().
CircularFifoQueue
is a first-in first-out queue with a fixed size that replaces its
oldest element if it is full.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With