Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FIFO Map with limited elements

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?

like image 395
davioooh Avatar asked Jun 07 '13 16:06

davioooh


2 Answers

You can do this with LinkedHashMap as follows:

new LinkedHashMap<K, V>(n) {
  @Override protected boolean removeEldestEntry(Entry<K, V> entry) {
    return size() > n;
  }
};
like image 87
Louis Wasserman Avatar answered Sep 29 '22 13:09

Louis Wasserman


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.

like image 40
yurin Avatar answered Sep 29 '22 12:09

yurin