Add and remove from MAP with limited size

≡放荡痞女 提交于 2019-12-12 01:37:04

问题


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)

回答1:


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()



来源:https://stackoverflow.com/questions/34453219/add-and-remove-from-map-with-limited-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!