FIFO Map with limited elements

davioooh picture davioooh · Jun 7, 2013 · Viewed 10.6k times · Source

I need a HashMap or simpy a Map with a fixed number of elements (n) working like a FIFO queue.

So until the element number is <= n new elements are simply put in the map.

For element number > n the first inserted element is removed and the newest is put in the map.

Is there something similar in Java, or do I have to implement it?

Answer

Louis Wasserman picture Louis Wasserman · Jun 7, 2013

You can do this with LinkedHashMap as follows:

new LinkedHashMap<K, V>(n) {
  @Override protected boolean removeEldestEntry(Entry<K, V> entry) {
    return size() > n;
  }
};