3

Which collection type in java should I use if I want to have something like Size-limited queue that holds last N elements in Java.

I have a list and I want to limit the size of the list to "100". So if i add the 101 th element in the list, the first element should be deleted automatically (FIFO). For example:

List<Item> items = ??;
items.add(item_1);
...
items.add(item_101); // implicitly calls items.remove(0);
items.add(item_102); // implicitly calls items.remove(0);
nimo23
  • 5,170
  • 10
  • 46
  • 75
  • 1
    Any list will do. Just wrap it into your own class to make sure this invariant is respected. – JB Nizet Sep 15 '17 at 08:47
  • 3
    Did I miss something? What makes your question different from the one, you have even linked yourself? – Holger Sep 15 '17 at 09:02
  • I am wondering if java 8 or 9 provides any kind of such a limited size list as is. – nimo23 Sep 15 '17 at 09:05
  • 1
    Apache commons provides [`CircularFifoQueue`](https://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/queue/CircularFifoQueue.html) – Flown Sep 15 '17 at 09:52

1 Answers1

4

You could try to write your own in 5 minutes actually, here is very dirty sketch I put up:

static class LFUList<T> extends AbstractCollection<T> {

    private final int size;

    private ArrayDeque<T> deque;

    public LFUList(int size) {
        super();
        this.size = size;
        deque = new ArrayDeque<>(size);
    }

    @Override
    public Iterator<T> iterator() {
        return deque.iterator();
    }

    @Override
    public int size() {
        return deque.size();
    }

    @Override
    public boolean add(T e) {
        if (deque.size() == size) {
            deque.pollFirst();
        }
        return deque.add(e);
    }

    @Override
    public boolean remove(Object o) {
        return deque.remove(o);
    }

}
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • does java not provide such kind of a limited size list out of the box? – nimo23 Sep 15 '17 at 09:06
  • @nimo23 I don't know of such a building-in functionality, no. – Eugene Sep 15 '17 at 09:06
  • 3
    I strongly recommend using `ArrayDeque` instead of `ArrayList`, as the former allows to remove from the beginning with the same efficiency as removing from the end. In contrast, `ArrayList` has to copy the entire array when removing the first element. – Holger Sep 15 '17 at 09:10
  • @Holger after lots of time, I needed this and updated :) – Eugene Sep 11 '18 at 10:09
  • @Eugene you are my hero! – Nick Sep 11 '18 at 10:09