在大小有限的MAP中添加和删除 [英] Add and remove from MAP with limited size
本文介绍了在大小有限的MAP中添加和删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个有限的地图,其中包含一些重复的键。达到大小后,我要删除最早的条目。
I want a limited size map with some duplicated keys. When size is reached I want delete the oldest entry.
例如,此数据集:
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?
他们的KEY是一个Long,也许我需要这样做吗? (效率不高)
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)
推荐答案
使用 LinkedListMultimap :它会保留插入顺序,因此删除最早的条目只是删除 entries()
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()
这篇关于在大小有限的MAP中添加和删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文