java - LinkedHashMap - 實現(xiàn)LRU

一、目的

通過LinkedHashMap實現(xiàn)LRU.

二、概念

LRU - Least Recently Used的縮寫,即最近最少使用.

三、核心

利用linkedHashMapremoveEldestEntry()以及accessOrder屬性.

removeEldestEntry(): 重新此方法,當(dāng)條件滿足為true時,刪除當(dāng)前map中最老的鍵值。

accessOrder:
true的時候,將按照操作后的元素放在鏈表后面放置順序就是訪問順序.
false的時候,將按照插入順序來遍歷.

四、具體實現(xiàn)

LRU實現(xiàn)類

public class LruTest<K, V> {
        private LinkedHashMap<K, V> lruMap;
        private float loadFactory = 0.75f;

        LruTest(int cap) {
            ConditionUtils.notNullWithFormat(cap, InCommonErrorCodeConstants.PARAM_IS_EMPTY, "cap");
            lruMap = new LinkedHashMap<K, V>(cap, loadFactory, true) {
                /**
                 *  put的時候,將移除map中最老的鍵和值
                 */
                @Override
                protected boolean removeEldestEntry(Map.Entry eldest) {
                    return super.size() > cap;
                }
            };
        }
        LruTest put(K key, V value) {
            lruMap.put(key, value);
            return this;
        }

        V get(K key){
            return lruMap.get(key);
        }

        Map<K,V> getMap(){
            return Safes.of(lruMap);
        }
    }

測試方法:

public static void main(String[] args) {
        LruTest<String, String> lruTest = new LruTest<>(3);
        lruTest.put("1","1");
        lruTest.put("2","2");
        lruTest.put("3","3");
        lruTest.put("4","4");

        System.out.println("測試直接添加的場景,刪除第一個節(jié)點 : " + JsonMoreUtils.toJson(lruTest.getMap()));
        lruTest.put("2","new2");
        lruTest.put("2","new22");
        lruTest.put("3","new3");
        lruTest.put("5","5");

        System.out.println("測試直接編輯后的場景,刪除未使用的key - 【 4 】 : " + JsonMoreUtils.toJson(lruTest.getMap()));
        lruTest.get("5");
        lruTest.get("2");
        lruTest.put("6","6");

        System.out.println("測試訪問的場景,刪除未訪問的key - 【 3 】 : " + JsonMoreUtils.toJson(lruTest.getMap()));
    }

結(jié)果:

測試直接添加的場景,刪除第一個節(jié)點 : {"2":"2","3":"3","4":"4"}
測試直接編輯后的場景,刪除未使用的key - 【 4 】 : {"2":"new22","3":"new3","5":"5"}
測試訪問的場景,刪除未訪問的key - 【 3 】 : {"5":"5","2":"new22","6":"6"}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容