LinkedHashMap的用法

LinkedHashMap,底层实现是在HashMap的基础上,添加了双向链表,可以根据访问顺序进行遍历,从最少访问到最频繁访问的升序访问。DOC描述如下:

LinkedHashMap(int,float,boolean) create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently access-order . This kind of map is well-suited to building LRU caches.

普通的LinkedHashMap

public class LinkedHashMapTest {

    public static void main(String[] args) {
        //插入顺序
        System.out.println("插入顺序");
        accessByInsertOrder();
    }
    
    /**
     * new LinkedHashMap<>(),与普通的HashMap相似,按键值哈希进行遍历
     */
    private static void accessByInsertOrder() {
        LinkedHashMap<String, Integer>  map = new LinkedHashMap<>();
        
        map.put("a", 1);
        map.put("b", 2);
        map.put("c", 3);
        map.put("a", 4);
        
        for(Entry<String, Integer> e : map.entrySet()) {
            System.out.println(e.getKey() + "-" +e.getValue());
        }
    }
}

输出:

插入顺序
a-4
b-2
c-3

按顺序访问进行遍历

public class LinkedHashMapTest {

    public static void main(String[] args) {
        //访问顺序
        System.out.println("访问顺序");
        accessByAccessOrder();
    }
    
    /**
     * new LinkedHashMap<>(16, 0.75f, true),accessOrder=true,表示按访问顺序进行遍历
     */
    private static void accessByAccessOrder() {
        LinkedHashMap<String, Integer>  map = new LinkedHashMap<>(16, 0.75f, true);
        
        map.put("a", 1);
        map.put("b", 2);
        map.put("c", 3);
        map.put("a", 4);
        
        for(Entry<String, Integer> e : map.entrySet()) {
            System.out.println(e.getKey() + "-" +e.getValue());
        }
    }
}

输出:最新访问的数据在后边

访问顺序
b-2
c-3
a-4

LRU缓存

同上一篇文章

public class LinkedHashMapTest {

    public static void main(String[] args) {
        //LRU缓存
        System.out.println("LRU顺序");
        LRUCache<String, Integer> cache = new LRUCache();
        for(int i = 0; i < 10; i++) {
            cache.put("a"+i, i+1);
        }
        cache.get("a0");
        cache.get("a1");
        cache.put("b", 10);
        
        for(Entry<String, Integer> e : cache.entrySet()) {
            System.out.println(e.getKey() + "-" +e.getValue());
        }
        
    }
    
    /**
     * 通过LinkedHashMap实现LRU缓存
     * @author Administrator
     *
     * @param <K>
     * @param <V>
     */
    static class LRUCache<K,V> extends LinkedHashMap<K,V>{
        
        static final int maxSize = 10;
        
        LRUCache(){
            super(16, 0.75f, true);
        }
        
        @Override
        protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
            return size() > maxSize;
        }
        
    }
}

输出:最新访问的数据在后边,其中a2-3被移除缓存

LRU顺序
a3-4
a4-5
a5-6
a6-7
a7-8
a8-9
a9-10
a0-1
a1-2
b-10

 

posted @ 2020-05-12 15:07  水木竹水  阅读(768)  评论(0编辑  收藏  举报