FIFO Map with limited elements

11,822

Solution 1

You can do this with LinkedHashMap as follows:

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

Solution 2

As I am on the side, where Java verbosity is its best feature... Below works for me:

public class FifoMap extends LinkedHashMap<String, String> {

    int max;

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public FifoMap (int max){
        super(max + 1);
        this.max = max;

    }

    @Override
    public String put (String key, String value) {
        String forReturn =  super.put(key, value);
        if (super.size() > max){
            removeEldest();
        }

        return forReturn;
    }

    private void removeEldest() {
        Iterator <String> iterator = this.keySet().iterator();
        if (iterator.hasNext()){
            this.remove(iterator.next());
        }
    }

}

It also works on Google App Engine that seems like has problem with Entry class.

Share:
11,822

Related videos on Youtube

davioooh
Author by

davioooh

Hi, I'm David Castelletti. I like to create things with Java &amp; Kotlin (❤). LinkedIn profile Personal Page + Blog (italian)

Updated on June 18, 2022

Comments

  • davioooh
    davioooh almost 2 years

    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?

  • The Original Android
    The Original Android over 8 years
    This is a good short way to remove oldest entry without sub-classing the class, LinkedHashMap.
  • Louis Wasserman
    Louis Wasserman over 8 years
    @TheOriginalAndroid, huh? You're absolutely subclassing LinkedHashMap.
  • qualebs
    qualebs almost 7 years
    This answer did it for me. big-up @yurin
  • Louis Wasserman
    Louis Wasserman over 6 years
    @fuyou001:. No. There's nothing built in that can be thread safe and do FIFO with eviction.