Arthur Arthur - 3 months ago 9
Java Question

Collection with limit and ability to remove old items before add new, if limit is reached

Who knows a collection with limit and ability to remove old items before add new, if limit is reached?

Old are the entries, which were placed at the beginning.

Answer

You should use org.apache.commons.collections4.queue.CircularFifoQueue from Apache Commons Collections with its constructor CircularFifoQueue(final int size).

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full. The removal order of a CircularFifoQueue 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.

Example:

class Test {
    public static void main(String[] args) {
        Queue<Integer> numbers = new CircularFifoQueue<>(2);
        for (int i = 0; i < 4; i++) {
            numbers.add(i);
            System.out.println("Iteration#" + i + " : " + numbers);
        }
    }
}

// Output:
// Iteration#0 : [0]
// Iteration#1 : [0, 1]
// Iteration#2 : [1, 2]
// Iteration#3 : [2, 3]