How to limit the maximum size of a Map by removing oldest entries when limit reached?
int MAX_SIZE = 5;
LinkedHashMap map = new LinkedHashMap<String, String[]>() {
@Override
protected boolean removeEldestEntry(final Map.Entry eldest) {
return size() > MAX_SIZE;
}
};
Example:
package zdemo;
import java.util.LinkedHashMap;
import java.util.Map;
public class ZDemo {
public static void main(String[] args) {
int MAX_SIZE = 5;
LinkedHashMap map = new LinkedHashMap<String, String[]>() {
@Override
protected boolean removeEldestEntry(final Map.Entry eldest) {
return size() > MAX_SIZE;
}
};
map.put("1", "x");
System.out.println(map);
map.put("2", "x");
System.out.println(map);
map.put("3", "x");
System.out.println(map);
map.put("4", "x");
System.out.println(map);
map.put("5", "x");
System.out.println(map);
map.put("6", "x");
System.out.println(map);
map.put("7", "x");
System.out.println(map);
map.put("8", "x");
System.out.println(map);
map.put("9", "x");
System.out.println(map);
map.put("10", "x");
System.out.println(map);
}
}
Output:
run:
{1=x}
{1=x, 2=x}
{1=x, 2=x, 3=x}
{1=x, 2=x, 3=x, 4=x}
{1=x, 2=x, 3=x, 4=x, 5=x}
{2=x, 3=x, 4=x, 5=x, 6=x}
{3=x, 4=x, 5=x, 6=x, 7=x}
{4=x, 5=x, 6=x, 7=x, 8=x}
{5=x, 6=x, 7=x, 8=x, 9=x}
{6=x, 7=x, 8=x, 9=x, 10=x}
BUILD SUCCESSFUL (total time: 0 seconds)
0 comments:
Post a Comment