2

I have map with some records. I want to restrict that map to only 5 elements and whenever a new element is added the first item should be removed and new element should be added in last position of map. Something similar to FIFO. Can anyone please suggest me a data structure to use or the solution itself.

E.g :

Map<String,String> map=new LinkedHashMap<String,String>(5);
for(int i=0;i<5;i++){
map.put(i+"",i+"");
}
map.put("5","5"); /* should remove map.get(0) and map.size will be still 5.Contents      would 1,2,3,4,5 */
  • 1
    This structure isn't a Map really, it's more like a Queue. Do you need to access elements in the middle of the map? – durron597 Nov 09 '12 at 05:49

1 Answers1

0

Take LinkedHashMap as the base class and override its removeEldestEntry method as described in the sample use of the method.

Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38