LRUMap,可以用来做缓存,它采用了LRU(least recently used)算法实现,简单的解释是,当Map达到最大容量后,会优先删除掉最不经常被用到的项。
maven
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
代码如下
import org.apache.commons.collections4.map.LRUMap;
import java.util.Map;
public class LRUMapTest {
public static void main(String[] args) {
Map map = new LRUMap<String,Integer>(4);
map.put("1", 1);
map.put("2", 2);
map.get("2");
map.put("3", 3);
map.put("4", 4);
map.put("5", 5);
java.util.Iterator it = map.keySet().iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
输出结果:
2
3
4
5