Search code examples
javadictionaryguavamultimap

Add and remove from MAP with limited size


I want a limited size map with some duplicated keys. When size is reached I want delete the oldest entry.

for example, this data set:

MAX_SIZE=5;
map.put(100,"OLDEST");
map.put(101,"XXXX");
map.put(101,"YYYY");
map.put(102,"ZZZZ");
map.put(103,"GGGG");

Then I want to insert a new entry in the map

myLength = map.size()
if(myLength>=MAX_SIZE){
   map.remove(the OLDEST)
}    
map.put(105,"NEW")

I was thinking in guava multimap, but how delete the oldest entry in multimap?

They KEY is a Long, maybe I need do a for? (not efficient)

oldest=MAX_LONG
for(Long key:map){
     if(key<oldest){
           oldest=key
      }
}
map.remove(oldest)

Solution

  • Use a LinkedListMultimap: it preserves the insertion order, so removing the oldest entry is just a matter of removing the first element of the list returned by entries()